code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def zip(self, *args): args = list(args) args.insert(0, self.obj) maxLen = _(args).chain().collect(lambda x, *args: len(x)).max().value() for i, v in enumerate(args): l = len(args[i]) if l < maxLen: args[i] for x in range(maxLen...
Zip together multiple lists into a single array -- elements that share an index go together.
def zipObject(self, values): result = {} keys = self.obj i = 0 l = len(keys) while i < l: result[keys[i]] = values[i] l = len(keys) i += 1 return self._wrap(result)
Zip together two arrays -- an array of keys and an array of values -- into a single object.
def indexOf(self, item, isSorted=False): array = self.obj ret = -1 if not (self._clean.isList() or self._clean.isTuple()): return self._wrap(-1) if isSorted: i = _.sortedIndex(array, item) ret = i if array[i] is item else -1 else: ...
Return the position of the first occurrence of an item in an array, or -1 if the item is not included in the array.
def lastIndexOf(self, item): array = self.obj i = len(array) - 1 if not (self._clean.isList() or self._clean.isTuple()): return self._wrap(-1) while i > -1: if array[i] is item: return self._wrap(i) i -= 1 return self....
Return the position of the last occurrence of an item in an array, or -1 if the item is not included in the array.
def range(self, *args): args = list(args) args.insert(0, self.obj) return self._wrap(range(*args))
Generate an integer Array containing an arithmetic progression.
def partial(self, *args): def part(*args2): args3 = args + args2 return self.obj(*args3) return self._wrap(part)
Partially apply a function by creating a version that has had some of its arguments pre-filled, without changing its dynamic `this` context.
def memoize(self, hasher=None): ns = self.Namespace() ns.memo = {} if hasher is None: hasher = lambda x: x def memoized(*args, **kwargs): key = hasher(*args) if key not in ns.memo: ns.memo[key] = self.obj(*args, **kwargs) ...
Memoize an expensive function by storing its results.
def delay(self, wait, *args): def call_it(): self.obj(*args) t = Timer((float(wait) / float(1000)), call_it) t.start() return self._wrap(self.obj)
Delays a function for the given number of milliseconds, and then calls it with the arguments supplied.
def throttle(self, wait): ns = self.Namespace() ns.timeout = None ns.throttling = None ns.more = None ns.result = None def done(): ns.more = ns.throttling = False whenDone = _.debounce(done, wait) wait = (float(wait) / float(1000)) ...
Returns a function, that, when invoked, will only be triggered at most once during a given window of time.
def debounce(self, wait, immediate=None): wait = (float(wait) / float(1000)) def debounced(*args, **kwargs): def call_it(): self.obj(*args, **kwargs) try: debounced.t.cancel() except(AttributeError): pass ...
Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing.
def once(self): ns = self.Namespace() ns.memo = None ns.run = False def work_once(*args, **kwargs): if ns.run is False: ns.memo = self.obj(*args, **kwargs) ns.run = True return ns.memo return self._wrap(work_once)
Returns a function that will be executed at most one time, no matter how often you call it. Useful for lazy initialization.
def wrap(self, wrapper): def wrapped(*args, **kwargs): if kwargs: kwargs["object"] = self.obj else: args = list(args) args.insert(0, self.obj) return wrapper(*args, **kwargs) return self._wrap(wrapped)
Returns the first function passed as an argument to the second, allowing you to adjust arguments, run code before and after, and conditionally execute the original function.
def compose(self, *args): args = list(args) def composed(*ar, **kwargs): lastRet = self.obj(*ar, **kwargs) for i in args: lastRet = i(lastRet) return lastRet return self._wrap(composed)
Returns a function that is the composition of a list of functions, each consuming the return value of the function that follows.
def after(self, func): ns = self.Namespace() ns.times = self.obj if ns.times <= 0: return func() def work_after(*args): if ns.times <= 1: return func(*args) ns.times -= 1 return self._wrap(work_after)
Returns a function that will only be executed after being called N times.
def pairs(self): keys = self._clean.keys() pairs = [] for key in keys: pairs.append([key, self.obj[key]]) return self._wrap(pairs)
Convert an object into a list of `[key, value]` pairs.
def invert(self): keys = self._clean.keys() inverted = {} for key in keys: inverted[self.obj[key]] = key return self._wrap(inverted)
Invert the keys and values of an object. The values must be serializable.
def functions(self): names = [] for i, k in enumerate(self.obj): if _(self.obj[k]).isCallable(): names.append(k) return self._wrap(sorted(names))
Return a sorted list of the function names available on the object.
def extend(self, *args): args = list(args) for i in args: self.obj.update(i) return self._wrap(self.obj)
Extend a given object with all the properties in passed-in object(s).
def pick(self, *args): ns = self.Namespace() ns.result = {} def by(key, *args): if key in self.obj: ns.result[key] = self.obj[key] _.each(self._flatten(args, True, []), by) return self._wrap(ns.result)
Return a copy of the object only containing the whitelisted properties.
def defaults(self, *args): ns = self.Namespace ns.obj = self.obj def by(source, *ar): for i, prop in enumerate(source): if prop not in ns.obj: ns.obj[prop] = source[prop] _.each(args, by) return self._wrap(ns.obj)
Fill in a given object with default properties.
def tap(self, interceptor): interceptor(self.obj) return self._wrap(self.obj)
Invokes interceptor with the obj, and then returns obj. The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain.
def isEmpty(self): if self.obj is None: return True if self._clean.isString(): ret = self.obj.strip() is "" elif self._clean.isDict(): ret = len(self.obj.keys()) == 0 else: ret = len(self.obj) == 0 return self._wrap(ret)
Is a given array, string, or object empty? An "empty" object has no enumerable own-properties.
def isFile(self): try: filetype = file except NameError: filetype = io.IOBase return self._wrap(type(self.obj) is filetype)
Check if the given object is a file
def join(self, glue=" "): j = glue.join([str(x) for x in self.obj]) return self._wrap(j)
Javascript's join implementation
def matches(self): def ret(obj, *args): if self.obj is obj: return True # avoid comparing an object to itself. for key in self.obj: if self.obj[key] != obj[key]: return False return True return self._wra...
Returns a predicate for checking whether an object has a given set of `key:value` pairs.
def times(self, func, *args): n = self.obj i = 0 while n is not 0: n -= 1 func(i) i += 1 return self._wrap(func)
Run a function **n** times.
def random(self, max_number=None): min_number = self.obj if max_number is None: min_number = 0 max_number = self.obj return random.randrange(min_number, max_number)
Return a random integer between min and max (inclusive).
def result(self, property, *args): if self.obj is None: return self._wrap(self.obj) if(hasattr(self.obj, property)): value = getattr(self.obj, property) else: value = self.obj.get(property) if _.isCallable(value): return self._wra...
If the value of the named property is a function then invoke it; otherwise, return it.
def mixin(self): methods = self.obj for i, k in enumerate(methods): setattr(underscore, k, methods[k]) self.makeStatic() return self._wrap(self.obj)
Add your own custom functions to the Underscore object, ensuring that they're correctly added to the OOP wrapper as well.
def uniqueId(self, prefix=""): _IdCounter.count += 1 id = _IdCounter.count if prefix: return self._wrap(prefix + str(id)) else: return self._wrap(id)
Generate a unique integer id (unique within the entire client session). Useful for temporary DOM ids.
def escape(self): # & must be handled first self.obj = self.obj.replace("&", self._html_escape_table["&"]) for i, k in enumerate(self._html_escape_table): v = self._html_escape_table[k] if k is not "&": self.obj = self.obj.replace(k, v) ...
Escape a string for HTML interpolation.
def unescape(self): for i, k in enumerate(self._html_escape_table): v = self._html_escape_table[k] self.obj = self.obj.replace(v, k) return self._wrap(self.obj)
Within an interpolation, evaluation, or escaping, remove HTML escaping that had been previously added.
def value(self): if self._wrapped is not self.Null: return self._wrapped else: return self.obj
returns the object instead of instance
def makeStatic(): p = lambda value: inspect.ismethod(value) or inspect.isfunction(value) for eachMethod in inspect.getmembers(underscore, predicate=p): m = eachMethod[0] if not hasattr(_, m): def caller(a): ...
Provide static access to underscore class
def init(): global _users, _names _configure_app(app) _users, _names = _init_login_manager(app) _configure_logger() init_scheduler(app.config.get('SQLALCHEMY_DATABASE_URI')) db.init(app.config.get('SQLALCHEMY_DATABASE_URI'))
Initialise and configure the app, database, scheduler, etc. This should be called once at application startup or at tests startup (and not e.g. called once for each test case).
def _configure_app(app_): app_.url_map.strict_slashes = False app_.config.from_object(default_settings) app_.config.from_envvar('JOB_CONFIG', silent=True) db_url = app_.config.get('SQLALCHEMY_DATABASE_URI') if not db_url: raise Exception('No db_url in config') app_.wsgi_app = ProxyF...
Configure the Flask WSGI app.
def _init_login_manager(app_): login_manager = flogin.LoginManager() login_manager.setup_app(app_) login_manager.anonymous_user = Anonymous login_manager.login_view = "login" users = {app_.config['USERNAME']: User('Admin', 0)} names = dict((int(v.get_id()), k) for k, v in users.items()) ...
Initialise and configure the login manager.
def _configure_logger_for_production(logger): stderr_handler = logging.StreamHandler(sys.stderr) stderr_handler.setLevel(logging.INFO) if 'STDERR' in app.config: logger.addHandler(stderr_handler) file_handler = logging.handlers.RotatingFileHandler( app.config.get('LOG_FILE'), maxBy...
Configure the given logger for production deployment. Logs to stderr and file, and emails errors to admins.
def _configure_logger(): if not app.debug: _configure_logger_for_production(logging.getLogger()) elif not app.testing: _configure_logger_for_debugging(logging.getLogger())
Configure the logging module.
def init_scheduler(db_uri): global scheduler scheduler = apscheduler.Scheduler() scheduler.misfire_grace_time = 3600 scheduler.add_jobstore( sqlalchemy_store.SQLAlchemyJobStore(url=db_uri), 'default') scheduler.add_listener( job_listener, events.EVENT_JOB_EXECUTED | even...
Initialise and configure the scheduler.
def user(): '''Show information about the current user :rtype: A dictionary with the following keys :param id: User id :type id: int :param name: User name :type name: string :param is_active: Whether the user is currently active :type is_active: bool :param is_anonymous: The anonym...
Show information about the current user :rtype: A dictionary with the following keys :param id: User id :type id: int :param name: User name :type name: string :param is_active: Whether the user is currently active :type is_active: bool :param is_anonymous: The anonymous user is the def...
def logout(): flogin.logout_user() next = flask.request.args.get('next') return flask.redirect(next or flask.url_for("user"))
Log out the active user
def clear_jobs(): '''Clear old jobs :param days: Jobs for how many days should be kept (default: 10) :type days: integer :statuscode 200: no error :statuscode 403: not authorized to delete jobs :statuscode 409: an error occurred ''' if not is_authorized(): return json.dumps({'e...
Clear old jobs :param days: Jobs for how many days should be kept (default: 10) :type days: integer :statuscode 200: no error :statuscode 403: not authorized to delete jobs :statuscode 409: an error occurred
def job_data(job_id): '''Get the raw data that the job returned. The mimetype will be the value provided in the metdata for the key ``mimetype``. **Results:** :rtype: string :statuscode 200: no error :statuscode 403: not authorized to view the job's data :statuscode 404: job id not found ...
Get the raw data that the job returned. The mimetype will be the value provided in the metdata for the key ``mimetype``. **Results:** :rtype: string :statuscode 200: no error :statuscode 403: not authorized to view the job's data :statuscode 404: job id not found :statuscode 409: an error...
def is_authorized(job=None): '''Returns true if the request is authorized for the job if provided. If no job is provided, the user has to be admin to be authorized. ''' if flogin.current_user.is_authenticated: return True if job: job_key = flask.request.headers.get('Authorization...
Returns true if the request is authorized for the job if provided. If no job is provided, the user has to be admin to be authorized.
def init(uri, echo=False): global ENGINE, _METADATA, JOBS_TABLE, METADATA_TABLE, LOGS_TABLE ENGINE = sqlalchemy.create_engine(uri, echo=echo, convert_unicode=True) _METADATA = sqlalchemy.MetaData(ENGINE) JOBS_TABLE = _init_jobs_table() METADATA_TABLE = _init_metadata_table() LOGS_TABLE = _i...
Initialise the database. Initialise the sqlalchemy engine, metadata and table objects that we use to connect to the database. Create the database and the database tables themselves if they don't already exist. :param uri: the sqlalchemy database URI :type uri: string :param echo: whether...
def _validate_error(error): if error is None: return None elif isinstance(error, basestring): return {"message": error} else: try: message = error["message"] if isinstance(message, basestring): return error else: ...
Validate and return the given error object. Based on the given error object, return either None or a dict with a "message" key whose value is a string (the dict may also have any other keys that it wants). The given "error" object can be: - None, in which case None is returned - A string, in...
def _update_job(job_id, job_dict): # Avoid SQLAlchemy "Unicode type received non-unicode bind param value" # warnings. if job_id: job_id = unicode(job_id) if "error" in job_dict: job_dict["error"] = _validate_error(job_dict["error"]) job_dict["error"] = json.dumps(job_dict[...
Update the database row for the given job_id with the given job_dict. All functions that update rows in the jobs table do it by calling this helper function. job_dict is a dict with values corresponding to the database columns that should be updated, e.g.: {"status": "complete", "data": ...}
def mark_job_as_completed(job_id, data=None): update_dict = { "status": "complete", "data": json.dumps(data), "finished_timestamp": datetime.datetime.now(), } _update_job(job_id, update_dict)
Mark a job as completed successfully. :param job_id: the job_id of the job to be updated :type job_id: unicode :param data: the output data returned by the job :type data: any JSON-serializable type (including None)
def mark_job_as_errored(job_id, error_object): update_dict = { "status": "error", "error": error_object, "finished_timestamp": datetime.datetime.now(), } _update_job(job_id, update_dict)
Mark a job as failed with an error. :param job_id: the job_id of the job to be updated :type job_id: unicode :param error_object: the error returned by the job :type error_object: either a string or a dict with a "message" key whose value is a string
def _init_jobs_table(): _jobs_table = sqlalchemy.Table( 'jobs', _METADATA, sqlalchemy.Column('job_id', sqlalchemy.UnicodeText, primary_key=True), sqlalchemy.Column('job_type', sqlalchemy.UnicodeText), sqlalchemy.Column('status', sqlalchemy.UnicodeText, index=True), sqlal...
Initialise the "jobs" table in the db.
def _init_metadata_table(): _metadata_table = sqlalchemy.Table( 'metadata', _METADATA, sqlalchemy.Column( 'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"), nullable=False, primary_key=True), sqlalchemy.Column('key', sqlalchemy.UnicodeText, prima...
Initialise the "metadata" table in the db.
def _init_logs_table(): _logs_table = sqlalchemy.Table( 'logs', _METADATA, sqlalchemy.Column( 'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"), nullable=False), sqlalchemy.Column('timestamp', sqlalchemy.DateTime), sqlalchemy.Column('mess...
Initialise the "logs" table in the db.
def _get_metadata(job_id): # Avoid SQLAlchemy "Unicode type received non-unicode bind param value" # warnings. job_id = unicode(job_id) results = ENGINE.execute( METADATA_TABLE.select().where( METADATA_TABLE.c.job_id == job_id)).fetchall() metadata = {} for row in resul...
Return any metadata for the given job_id from the metadata table.
def _get_logs(job_id): # Avoid SQLAlchemy "Unicode type received non-unicode bind param value" # warnings. job_id = unicode(job_id) results = ENGINE.execute( LOGS_TABLE.select().where(LOGS_TABLE.c.job_id == job_id)).fetchall() results = [dict(result) for result in results] for re...
Return any logs for the given job_id from the logs table.
def check_node_attributes(pattern, node, *attributes): for attribute_name in attributes: attribute = node.get(attribute_name) if attribute is not None and pattern.search(attribute): return True return False
Searches match in attributes against given pattern and if finds the match against any of them returns True.
def generate_hash_id(node): try: content = tostring(node) except Exception: logger.exception("Generating of hash failed") content = to_bytes(repr(node)) hash_id = md5(content).hexdigest() return hash_id[:8]
Generates a hash_id for the node in question. :param node: lxml etree node
def get_link_density(node, node_text=None): if node_text is None: node_text = node.text_content() node_text = normalize_whitespace(node_text.strip()) text_length = len(node_text) if text_length == 0: return 0.0 links_length = sum(map(_get_normalized_text_length, node.findall("...
Computes the ratio for text in given node and text in links contained in the node. It is computed from number of characters in the texts. :parameter Element node: HTML element in which links density is computed. :parameter string node_text: Text content of given node if it was obtained ...
def get_class_weight(node): weight = 0 if check_node_attributes(CLS_WEIGHT_NEGATIVE, node, "class"): weight -= 25 if check_node_attributes(CLS_WEIGHT_POSITIVE, node, "class"): weight += 25 if check_node_attributes(CLS_WEIGHT_NEGATIVE, node, "id"): weight -= 25 if check...
Computes weight of element according to its class/id. We're using sets to help efficiently check for existence of matches.
def is_unlikely_node(node): unlikely = check_node_attributes(CLS_UNLIKELY, node, "class", "id") maybe = check_node_attributes(CLS_MAYBE, node, "class", "id") return bool(unlikely and not maybe and node.tag != "body")
Short helper for checking unlikely status. If the class or id are in the unlikely list, and there's not also a class/id in the likely list then it might need to be removed.
def cached_property(getter): def decorator(self): key = "_cached_property_" + getter.__name__ if not hasattr(self, key): setattr(self, key, getter(self)) return getattr(self, key) decorator.__name__ = getter.__name__ decorator.__module__ = getter.__module__ de...
Decorator that converts a method into memoized property. The decorator works as expected only for classes with attribute '__dict__' and immutable properties.
def clear(self): self.filename = '' self.filehandler = 0 # Station name, identification and revision year: self.station_name = '' self.rec_dev_id = '' self.rev_year = 0000 # Number and type of channels: self.TT = 0 self.A = 0 # Number of a...
Clear the internal (private) variables of the class.
def getTime(self): T = 1/float(self.samp[self.nrates-1]) endtime = self.endsamp[self.nrates-1] * T t = numpy.linspace(0,endtime,self.endsamp[self.nrates-1]) return t
Actually, this function creates a time stamp vector based on the number of samples and sample rate.
def getAnalogID(self,num): listidx = self.An.index(num) # Get the position of the channel number. return self.Ach_id[listidx]
Returns the COMTRADE ID of a given channel number. The number to be given is the same of the COMTRADE header.
def getDigitalID(self,num): listidx = self.Dn.index(num) # Get the position of the channel number. return self.Dch_id[listidx]
Reads the COMTRADE ID of a given channel number. The number to be given is the same of the COMTRADE header.
def getAnalogType(self,num): listidx = self.An.index(num) unit = self.uu[listidx] if unit == 'kV' or unit == 'V': return 'V' elif unit == 'A' or unit == 'kA': return 'I' else: print 'Unknown channel type' return 0
Returns the type of the channel 'num' based on its unit stored in the Comtrade header file. Returns 'V' for a voltage channel and 'I' for a current channel.
def getAnalogUnit(self,num): listidx = self.An.index(num) # Get the position of the channel number. return self.uu[listidx]
Returns the COMTRADE channel unit (e.g., kV, V, kA, A) of a given channel number. The number to be given is the same of the COMTRADE header.
def ReadDataFile(self): if os.path.isfile(self.filename[0:-4] + '.dat'): filename = self.filename[0:-4] + '.dat' elif os.path.isfile(self.filename[0:-4] + '.DAT'): filename = self.filename[0:-4] + '.DAT' else: print "Data file File not f...
Reads the contents of the Comtrade .dat file and store them in a private variable. For accessing a specific channel data, see methods getAnalogData and getDigitalData.
def getAnalogChannelData(self,ChNumber): if not self.DatFileContent: print "No data file content. Use the method ReadDataFile first" return 0 if (ChNumber > self.A): print "Channel number greater than the total number of channels." retur...
Returns an array of numbers containing the data values of the channel number "ChNumber". ChNumber is the number of the channal as in .cfg file.
def getDigitalChannelData(self,ChNumber): if not self.DatFileContent: print "No data file content. Use the method ReadDataFile first" return 0 if (ChNumber > self.D): print "Digital channel number greater than the total number of channels." ...
Returns an array of numbers (0 or 1) containing the values of the digital channel status. ChNumber: digital channel number.
def initLogger(): ''' This code taken from Matt's Suspenders for initializing a logger ''' global logger logger = logging.getLogger('root') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) formatter = logging.Formatter("[%(asctime)s] %(l...
This code taken from Matt's Suspenders for initializing a logger
def decompressBWTPoolProcess(tup): ''' Individual process for decompression ''' (inputDir, outputDir, startIndex, endIndex) = tup if startIndex == endIndex: return True #load the thing we'll be extracting from msbwt = MultiStringBWT.CompressedMSBWT() msbwt.loadMsbwt(inp...
Individual process for decompression
def clearAuxiliaryData(dirName): ''' This function removes auxiliary files associated with a given filename ''' if dirName != None: if os.path.exists(dirName+'/auxiliary.npy'): os.remove(dirName+'/auxiliary.npy') if os.path.exists(dirName+'/totalCounts.p'): ...
This function removes auxiliary files associated with a given filename
def ok_embedded_video(node): good_keywords = ('youtube', 'blip.tv', 'vimeo') node_str = tounicode(node) for key in good_keywords: if key in node_str: return True return False
Check if this embed/video is an ok one to count.
def build_base_document(dom, return_fragment=True): body_element = dom.find(".//body") if body_element is None: fragment = fragment_fromstring('<div id="readabilityBody"/>') fragment.append(dom) else: body_element.tag = "div" body_element.set("id", "readabilityBody") ...
Builds a base document with the body as root. :param dom: Parsed lxml tree (Document Object Model). :param bool return_fragment: If True only <div> fragment is returned. Otherwise full HTML document is returned.
def check_siblings(candidate_node, candidate_list): candidate_css = candidate_node.node.get("class") potential_target = candidate_node.content_score * 0.2 sibling_target_score = potential_target if potential_target > 10 else 10 parent = candidate_node.node.getparent() siblings = parent.getchild...
Looks through siblings for content that might also be related. Things like preambles, content split by ads that we removed, etc.
def clean_document(node): if node is None or len(node) == 0: return None logger.debug("\n\n-------------- CLEANING DOCUMENT -----------------") to_drop = [] for n in node.iter(): # clean out any in-line style properties if "style" in n.attrib: n.set("style", ""...
Cleans up the final document we return as the readable article.
def find_candidates(document): nodes_to_score = set() should_remove = set() for node in document.iter(): if is_unlikely_node(node): logger.debug( "We should drop unlikely: %s %r", node.tag, node.attrib) should_remove.add(node) elif is_bad_link(no...
Finds cadidate nodes for the readable version of the article. Here's we're going to remove unlikely nodes, find scores on the rest, clean up and return the final best match.
def is_bad_link(node): if node.tag != "a": return False name = node.get("name") href = node.get("href") if name and not href: return True if href: href_parts = href.split("#") if len(href_parts) == 2 and len(href_parts[1]) > 25: return True ret...
Helper to determine if the node is link that is useless. We've hit articles with many multiple links that should be cleaned out because they're just there to pollute the space. See tests for examples.
def leaf_div_elements_into_paragraphs(document): for element in document.iter(tag="div"): child_tags = tuple(n.tag for n in element.getchildren()) if "div" not in child_tags and "p" not in child_tags: logger.debug( "Changing leaf block element <%s> into <p>", element...
Turn some block elements that don't have children block level elements into <p> elements. Since we can't change the tree as we iterate over it, we must do this before we process our document.
def dom(self): try: dom = self._original_document.dom # cleaning doesn't return, just wipes in place html_cleaner(dom) return leaf_div_elements_into_paragraphs(dom) except ValueError: return None
Parsed lxml tree (Document Object Model) of the given html.
def candidates(self): dom = self.dom if dom is None or len(dom) == 0: return None candidates, unlikely_candidates = find_candidates(dom) drop_nodes_with_parents(unlikely_candidates) return candidates
Generates list of candidates from the DOM.
def _readable(self): if not self.candidates: logger.info("No candidates found in document.") return self._handle_no_candidates() # right now we return the highest scoring candidate content best_candidates = sorted( (c for c in self.candidates.values(...
The readable parsed article
def _handle_no_candidates(self): # since we've not found a good candidate we're should help this if self.dom is not None and len(self.dom): dom = prep_article(self.dom) dom = build_base_document(dom, self._return_fragment) return self._remove_orphans( ...
If we fail to find a good candidate we need to find something else.
def parse(cls, dom): handler = cls() saxify(dom, handler) return handler.content
Converts DOM into paragraphs.
def fastaIterator(fastaFN): ''' Iterator that yields tuples containing a sequence label and the sequence itself @param fastaFN - the FASTA filename to open and parse @return - an iterator yielding tuples of the form (label, sequence) from the FASTA file ''' if fastaFN[len(fastaFN)-3:] == '.gz': ...
Iterator that yields tuples containing a sequence label and the sequence itself @param fastaFN - the FASTA filename to open and parse @return - an iterator yielding tuples of the form (label, sequence) from the FASTA file
def loadBWT(bwtDir, logger=None): ''' Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression and assign the appropriate class preferring the decompressed version if both exist. @return - a MultiStringBWT, CompressedBWT, or none if neith...
Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression and assign the appropriate class preferring the decompressed version if both exist. @return - a MultiStringBWT, CompressedBWT, or none if neither can be instantiated
def parseProfileLine(fp): ''' Helper function for profile parsing @param fp - the file pointer to get the next line from @return - (kmer, kmerCount) as (string, int) ''' nextLine = fp.readline() if nextLine == None or nextLine == '': return (None, None) else: pieces = nex...
Helper function for profile parsing @param fp - the file pointer to get the next line from @return - (kmer, kmerCount) as (string, int)
def reverseComplement(seq): ''' Helper function for generating reverse-complements ''' revComp = '' complement = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N', '$':'$'} for c in reversed(seq): revComp += complement[c] return revComf reverseComplement(seq): ''' Helper function ...
Helper function for generating reverse-complements
def constructIndexing(self): ''' This helper function calculates the start and end index for each character in the BWT. Basically, the information generated here is for quickly finding offsets. This is run AFTER self.constructTotalCounts(...) ''' #mark starts and ends of key el...
This helper function calculates the start and end index for each character in the BWT. Basically, the information generated here is for quickly finding offsets. This is run AFTER self.constructTotalCounts(...)
def getSequenceDollarID(self, strIndex, returnOffset=False): ''' This will take a given index and work backwards until it encounters a '$' indicating which dollar ID is associated with this read @param strIndex - the index of the character to start with @return - an integer indic...
This will take a given index and work backwards until it encounters a '$' indicating which dollar ID is associated with this read @param strIndex - the index of the character to start with @return - an integer indicating the dollar ID of the string the given character belongs to
def getOccurrenceOfCharAtIndex(self, sym, index): ''' This functions gets the FM-index value of a character at the specified position @param sym - the character to find the occurrence level @param index - the index we want to find the occurrence level at @return - the number of o...
This functions gets the FM-index value of a character at the specified position @param sym - the character to find the occurrence level @param index - the index we want to find the occurrence level at @return - the number of occurrences of char before the specified index
def getFullFMAtIndex(self, index): ''' This function creates a complete FM-index for a specific position in the BWT. Example using the above example: BWT Full FM-index $ A C G T C 0 1 2 4 4 $ 0 1 3 4 4 C 1 1 3 4 4 A ...
This function creates a complete FM-index for a specific position in the BWT. Example using the above example: BWT Full FM-index $ A C G T C 0 1 2 4 4 $ 0 1 3 4 4 C 1 1 3 4 4 A 1 1 4 4 4 1 2 4 4 4 @return -...
def loadMsbwt(self, dirName, logger): ''' This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory @param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail ''' #open the file ...
This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory @param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail
def getBWTRange(self, start, end): ''' This function masks the complexity of retrieving a chunk of the BWT from the compressed format @param start - the beginning of the range to retrieve @param end - the end of the range in normal python notation (bwt[end] is not part of the return) ...
This function masks the complexity of retrieving a chunk of the BWT from the compressed format @param start - the beginning of the range to retrieve @param end - the end of the range in normal python notation (bwt[end] is not part of the return) @return - a range of integers representing the cha...
def decode_html(html): if isinstance(html, unicode): return html match = CHARSET_META_TAG_PATTERN.search(html) if match: declared_encoding = match.group(1).decode("ASCII") # proceed unknown encoding as if it wasn't found at all with ignored(LookupError): ret...
Converts bytes stream containing an HTML page into Unicode. Tries to guess character encoding from meta tag of by "chardet" library.
def build_document(html_content, base_href=None): assert html_content is not None if isinstance(html_content, unicode): html_content = html_content.encode("utf8", "xmlcharrefreplace") try: document = document_fromstring(html_content, parser=UTF8_PARSER) except (ParserError, XMLSyn...
Requires that the `html_content` not be None
def _parse_properties(self): props_dict = self.data.get('properties', {}) for prop_name in self.KNOWN_PROPERTIES: if prop_name in props_dict: setattr(self, prop_name, props_dict.get(prop_name)) else: setattr(self, prop_name, None)
Nodes have properties, which are facts like the name, description, url etc. Loop through each of them and set it as attributes on this company so that we can make calls like company.name person.description
def _parse_relationship(self): rs_dict = self.data.get('relationships', {}) for rs_name in self.KNOWN_RELATIONSHIPS: if rs_name in rs_dict: setattr( self, rs_name, Relationship(rs_name, rs_dict.get(rs_name))) else: # fi...
Nodes have Relationships, and similarly to properties, we set it as an attribute on the Organization so we can make calls like company.current_team person.degrees
def open(self): self.startTime = datetime.datetime.now() self.offset = 0 return self
Reset time and counts.