code
stringlengths
1
18.2k
def decompress(self, value): """ Retreieve each field value or provide the initial values """ if value: return [value.get(field.name, None) for field in self.fields] return [field.field.initial for field in self.fields]
def format_label(self, field, counter): """ Format the label for each field """ return '<label for="id_formfield_%s" %s>%s</label>' % ( counter, field.field.required and 'class="required"', field.label)
def format_output(self, rendered_widgets): """ This output will yeild all widgets grouped in a un-ordered list """ ret = [u'<ul class="formfield">'] for i, field in enumerate(self.fields): label = self.format_label(field, i) help_text = self.format_help_text(field, i) ret.append(u'<li>%s %s %s</li>' % ( label, rendered...
def sentiment(self): """ Returns average sentiment of document. Must have sentiment enabled in XML output. :getter: returns average sentiment of the document :type: float """ if self._sentiment is None: results = self._xml.xpath('/root/document/sentences') self._sentiment = float(results[0].get("averageSentiment", 0)) ...
def _get_sentences_dict(self): """ Returns sentence objects :return: order dict of sentences :rtype: collections.OrderedDict """ if self._sentences_dict is None: sentences = [Sentence(element) for element in self._xml.xpath('/root/document/sentences/sentence')] self._sentences_dict = OrderedDict([(s.id, s) for s in sen...
def coreferences(self): """ Returns a list of Coreference classes :getter: Returns a list of coreferences :type: list of corenlp_xml.coreference.Coreference """ if self._coreferences is None: coreferences = self._xml.xpath('/root/document/coreference/coreference') if len(coreferences) > 0: self._coreferences = [Corefer...
def id(self): """ :return: the ID attribute of the sentence :rtype: int """ if self._id is None: self._id = int(self._element.get('id')) return self._id
def sentiment(self): """ The sentiment of this sentence :getter: Returns the sentiment value of this sentence :type: int """ if self._sentiment is None: self._sentiment = int(self._element.get('sentiment')) return self._sentiment
def _get_tokens_dict(self): """ Accesses tokens dict :return: The ordered dict of the tokens :rtype: collections.OrderedDict """ if self._tokens_dict is None: tokens = [Token(element) for element in self._element.xpath('tokens/token')] self._tokens_dict = OrderedDict([(t.id, t) for t in tokens]) return self._tokens_dic...
def subtrees_for_phrase(self, phrase_type): """ Returns subtrees corresponding all phrases matching a given phrase type :param phrase_type: POS such as "NP", "VP", "det", etc. :type phrase_type: str :return: a list of NLTK.Tree.Subtree instances :rtype: list of NLTK.Tree.Subtree """ return [subtree for subtree in self....
def phrase_strings(self, phrase_type): """ Returns strings corresponding all phrases matching a given phrase type :param phrase_type: POS such as "NP", "VP", "det", etc. :type phrase_type: str :return: a list of strings representing those phrases """ return [u" ".join(subtree.leaves()) for subtree in self.subtrees_for_...
def parse_string(self): """ Accesses the S-Expression parse string stored on the XML document :getter: Returns the parse string :type: str """ if self._parse_string is None: parse_text = self._element.xpath('parse/text()') if len(parse_text) > 0: self._parse_string = parse_text[0] return self._parse_string
def parse(self): """ Accesses the parse tree based on the S-expression parse string in the XML :getter: Returns the NLTK parse tree :type: nltk.Tree """ if self.parse_string is not None and self._parse is None: self._parse = Tree.parse(self._parse_string) return self._parse
def basic_dependencies(self): """ Accesses basic dependencies from the XML output :getter: Returns the dependency graph for basic dependencies :type: corenlp_xml.dependencies.DependencyGraph """ if self._basic_dependencies is None: deps = self._element.xpath('dependencies[@type="basic-dependencies"]') if len(deps) > 0:...
def collapsed_dependencies(self): """ Accessess collapsed dependencies for this sentence :getter: Returns the dependency graph for collapsed dependencies :type: corenlp_xml.dependencies.DependencyGraph """ if self._basic_dependencies is None: deps = self._element.xpath('dependencies[@type="collapsed-dependencies"]') if...
def collapsed_ccprocessed_dependencies(self): """ Accesses collapsed, CC-processed dependencies :getter: Returns the dependency graph for collapsed and cc processed dependencies :type: corenlp_xml.dependencies.DependencyGraph """ if self._basic_dependencies is None: deps = self._element.xpath('dependencies[@type="colla...
def word(self): """ Lazy-loads word value :getter: Returns the plain string value of the word :type: str """ if self._word is None: words = self._element.xpath('word/text()') if len(words) > 0: self._word = words[0] return self._word
def lemma(self): """ Lazy-loads the lemma for this word :getter: Returns the plain string value of the word lemma :type: str """ if self._lemma is None: lemmata = self._element.xpath('lemma/text()') if len(lemmata) > 0: self._lemma = lemmata[0] return self._lemma
def character_offset_begin(self): """ Lazy-loads character offset begin node :getter: Returns the integer value of the beginning offset :type: int """ if self._character_offset_begin is None: offsets = self._element.xpath('CharacterOffsetBegin/text()') if len(offsets) > 0: self._character_offset_begin = int(offsets[0])...
def character_offset_end(self): """ Lazy-loads character offset end node :getter: Returns the integer value of the ending offset :type: int """ if self._character_offset_end is None: offsets = self._element.xpath('CharacterOffsetEnd/text()') if len(offsets) > 0: self._character_offset_end = int(offsets[0]) return self....
def pos(self): """ Lazy-loads the part of speech tag for this word :getter: Returns the plain string value of the POS tag for the word :type: str """ if self._pos is None: poses = self._element.xpath('POS/text()') if len(poses) > 0: self._pos = poses[0] return self._pos
def ner(self): """ Lazy-loads the NER for this word :getter: Returns the plain string value of the NER tag for the word :type: str """ if self._ner is None: ners = self._element.xpath('NER/text()') if len(ners) > 0: self._ner = ners[0] return self._ner
def speaker(self): """ Lazy-loads the speaker for this word :getter: Returns the plain string value of the speaker tag for the word :type: str """ if self._speaker is None: speakers = self._element.xpath('Speaker/text()') if len(speakers) > 0: self._speaker = speakers[0] return self._speaker
def _generate_iam_role_policy(self): """ Generate the policy for the IAM Role. Terraform name: aws_iam_role.lambda_role """ endpoints = self.config.get('endpoints') queue_arns = [] for ep in endpoints: for qname in endpoints[ep]['queues']: qarn = 'arn:aws:sqs:%s:%s:%s' % (self.aws_region, self.aws_account_id, qname) if...
def _generate_iam_invoke_role_policy(self): """ Generate the policy for the IAM role used by API Gateway to invoke the lambda function. Terraform name: aws_iam_role.invoke_role """ invoke_pol = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Resource": ["*"], "Action": ["lambda:InvokeFunction"] } ] } se...
def _generate_iam_role(self): """ Generate the IAM Role needed by the Lambda function. Terraform name: aws_iam_role.lambda_role """ pol = { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "lambda.amazonaws.com" }, "Effect": "Allow", "Sid": "" } ] } self.tf_conf['resource'...
def _generate_iam_invoke_role(self): """ Generate the IAM Role for API Gateway to use to invoke the function. Terraform name: aws_iam_role.invoke_role :return: """ invoke_assume = { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "apigateway.amazonaws.com" }, "Effect": "A...
def _generate_lambda(self): """ Generate the lambda function and its IAM role, and add to self.tf_conf """ self.tf_conf['resource']['aws_lambda_function']['lambda_func'] = { 'filename': 'webhook2lambda2sqs_func.zip', 'function_name': self.resource_name, 'role': '${aws_iam_role.lambda_role.arn}', 'handler': 'webhook2lam...
def _set_account_info(self): """ Connect to the AWS IAM API via boto3 and run the GetUser operation on the current user. Use this to set ``self.aws_account_id`` and ``self.aws_region``. """ if 'AWS_DEFAULT_REGION' in os.environ: logger.debug('Connecting to IAM with region_name=%s', os.environ['AWS_DEFAULT_REGION']) kwa...
def _generate_api_gateway(self): """ Generate the full configuration for the API Gateway, and add to self.tf_conf """ self.tf_conf['resource']['aws_api_gateway_rest_api']['rest_api'] = { 'name': self.resource_name, 'description': self.description } self.tf_conf['output']['rest_api_id'] = { 'value': '${aws_api_gateway_r...
def _generate_api_gateway_deployment(self): """ Generate the API Gateway Deployment/Stage, and add to self.tf_conf """ # finally, the deployment # this resource MUST come last dep_on = [] for rtype in sorted(self.tf_conf['resource'].keys()): for rname in sorted(self.tf_conf['resource'][rtype].keys()): dep_on.append('%s...
def _generate_endpoint(self, ep_name, ep_method): """ Generate configuration for a single endpoint (this is many resources) Terraform Names: - aws_api_gateway_resource: {ep_name} - aws_api_gateway_method: {ep_name}_{ep_method} :param ep_name: endpoint name (path component) :type ep_name: str :param ep_method: HTTP meth...
{ 'rest_api_id': '${aws_api_gateway_rest_api.rest_api.id}', 'resource_id': '${aws_api_gateway_resource.%s.id}' % ep_name, 'http_method': ep_method, 'status_code': 500, 'response_models': { 'application/json': '${aws_api_gateway_model.errormessage.name}', }, 'depends_on': [ 'aws_api_gateway_method.%s_%s' % (ep_name, ep_...
def _get_config(self, func_src): """ Return the full terraform configuration as a JSON string :param func_src: lambda function source :type func_src: str :return: terraform configuration :rtype: str """ self._set_account_info() self._generate_iam_role() self._generate_iam_role_policy() self._generate_iam_invoke_role() ...
def _write_zip(self, func_src, fpath): """ Write the function source to a zip file, suitable for upload to Lambda. Note there's a bit of undocumented magic going on here; Lambda needs the execute bit set on the module with the handler in it (i.e. 0755 or 0555 permissions). There doesn't seem to be *any* documentation o...
zipinfo date to: %s', zi_tup) # create a ZipInfo so we can set file attributes/mode zinfo = zipfile.ZipInfo('webhook2lambda2sqs_func.py', zi_tup) # set file mode zinfo.external_attr = 0x0755 << 16 logger.debug('setting zipinfo file mode to: %s', zinfo.external_attr) logger.debug('writing zip file at: %s', fpath) with z...
def generate(self, func_src): """ Generate TF config and write to ./webhook2lambda2sqs.tf.json; write the lambda function to ./webhook2lambda2sqs_func.py :param func_src: lambda function source :type func_src: str """ # write function source for reference logger.warning('Writing lambda function source to: ' './webhook2...
def none_missing(df, columns=None): """ Asserts that there are no missing values (NaNs) in the DataFrame. """ if columns is None: columns = df.columns assert not df[columns].isnull().any().any() return df
def within_set(df, items=None): """ Assert that df is a subset of items Parameters ========== df : DataFrame items : dict mapping of columns (k) to array-like of values (v) that ``df[k]`` is expected to be a subset of """ for k, v in items.items(): if not df[k].isin(v).all(): raise AssertionError return df
def within_range(df, items=None): """ Assert that a DataFrame is within a range. Parameters ========== df : DataFame items : dict mapping of columns (k) to a (low, high) tuple (v) that ``df[k]`` is expected to be between. """ for k, (lower, upper) in items.items(): if (lower > df[k]).any() or (upper < df[k]).any(): rai...
def zmanim(self): """Return a dictionary of the zmanim the object represents.""" return {key: self.utc_minute_timezone(value) for key, value in self.get_utc_sun_time_full().items()}
def candle_lighting(self): """Return the time for candle lighting, or None if not applicable.""" today = HDate(gdate=self.date, diaspora=self.location.diaspora) tomorrow = HDate(gdate=self.date + dt.timedelta(days=1), diaspora=self.location.diaspora) # If today is a Yom Tov or Shabbat, and tomorrow is a Yom Tov or # Sh...
def _havdalah_datetime(self): """Compute the havdalah time based on settings.""" if self.havdalah_offset == 0: return self.zmanim["three_stars"] # Otherwise, use the offset. return (self.zmanim["sunset"] + dt.timedelta(minutes=self.havdalah_offset))
def havdalah(self): """Return the time for havdalah, or None if not applicable. If havdalah_offset is 0, uses the time for three_stars. Otherwise, adds the offset to the time of sunset and uses that. If it's currently a multi-day YomTov, and the end of the stretch is after today, the havdalah value is defined to be Non...
tomorrow.is_shabbat or tomorrow.is_yom_tov: return None return self._havdalah_datetime return None
def issur_melacha_in_effect(self): """At the given time, return whether issur melacha is in effect.""" # TODO: Rewrite this in terms of candle_lighting/havdalah properties. weekday = self.date.weekday() tomorrow = self.date + dt.timedelta(days=1) tomorrow_holiday_type = HDate( gdate=tomorrow, diaspora=self.location.dia...
def gday_of_year(self): """Return the number of days since January 1 of the given year.""" return (self.date - dt.date(self.date.year, 1, 1)).days
def utc_minute_timezone(self, minutes_from_utc): """Return the local time for a given time UTC.""" from_zone = tz.gettz('UTC') to_zone = self.location.timezone utc = dt.datetime.combine(self.date, dt.time()) + \ dt.timedelta(minutes=minutes_from_utc) utc = utc.replace(tzinfo=from_zone) local = utc.astimezone(to_zone) r...
def _get_utc_sun_time_deg(self, deg): """ Return the times in minutes from 00:00 (utc) for a given sun altitude. This is done for a given sun altitude in sunrise `deg` degrees This function only works for altitudes sun really is. If the sun never gets to this altitude, the returned sunset and sunrise values will be neg...
# sun declanation hour_angle = 0 # solar hour angle sunrise_angle = math.pi * deg / 180.0 # sun angle at sunrise/set # get the day of year day_of_year = self.gday_of_year() # get radians of sun orbit around earth =) gama = 2.0 * math.pi * ((day_of_year - 1) / 365.0) # get the diff betwen suns clock and wall clock in mi...
* math.sin(3.0 * gama)) # we use radians, ratio is 2pi/360 latitude = math.pi * self.location.latitude / 180.0 # the sun real time diff from noon at sunset/rise in radians try: hour_angle = (math.acos( math.cos(sunrise_angle) / (math.cos(latitude) * math.cos(decl)) - math.tan(latitude) * math.tan(decl))) # check for to...
def get_utc_sun_time_full(self): """Return a list of Jewish times for the given location.""" # sunset and rise time sunrise, sunset = self._get_utc_sun_time_deg(90.833) # shaa zmanit by gara, 1/12 of light time sun_hour = (sunset - sunrise) // 12 midday = (sunset + sunrise) // 2 # get times of the different sun angles ...
+ 12 * 60.) return res
def cutoff(s, length=120): """Cuts a given string if it is longer than a given length.""" if length < 5: raise ValueError('length must be >= 5') if len(s) <= length: return s else: i = (length - 2) / 2 j = (length - 3) / 2 return s[:i] + '...' + s[-j:]
def save(self, reload=False): """Save changes to the file.""" self.wrapper.raw.save() if reload: self.reload()
def pprint(self, raw=False): """Print the metadata in a human-friendly form. if *raw* is *True*, print the unmodified keys and values. """ tags = self.wrapper if not raw else self.wrapper.raw print u'{}:'.format(self.path) names = tags.keys() names.sort() w = max(len(k) for k in names) fmt = u' {{:<{}}} : {{}}'.format(...
def rebase(self, text, char='X'): """ Rebases text with stop words removed. """ regexp = re.compile(r'\b(%s)\b' % '|'.join(self.collection), re.IGNORECASE | re.UNICODE) def replace(m): word = m.group(1) return char * len(word) return regexp.sub(replace, text)
def _loop_wrapper_func(func, args, shared_mem_run, shared_mem_pause, interval, sigint, sigterm, name, logging_level, conn_send, func_running, log_queue): """ to be executed as a separate process (that's why this functions is declared static) """ prefix = get_identifier(name) + ' ' global log log = logging.getLogger(__n...
to InterruptedError") break func_running.value = False if error: sys.exit(-1) else: log.debug("wrapper_func terminates gracefully") # gets rid of the following warnings # Exception ignored in: <_io.FileIO name='/dev/null' mode='rb'> # ResourceWarning: unclosed file <_io.TextIOWrapper name='/dev/null' mode='r' encoding=...
def show_stat_base(count_value, max_count_value, prepend, speed, tet, ttg, width, **kwargs): """A function that formats the progress information This function will be called periodically for each progress that is monitored. Overwrite this function in a subclass to implement a specific formating of the progress informat...
def _show_stat_wrapper_Progress(count, last_count, start_time, max_count, speed_calc_cycles, width, q, last_speed, prepend, show_stat_function, add_args, i, lock): """ calculate """ count_value, max_count_value, speed, tet, ttg, = Progress._calc(count, last_count, start_time, max_count, speed_calc_cycles, q, last_speed...
def _show_stat_wrapper_multi_Progress(count, last_count, start_time, max_count, speed_calc_cycles, width, q, last_speed, prepend, show_stat_function, len_, add_args, lock, info_line, no_move_up=False): """ call the static method show_stat_wrapper for each process """ # print(ESC_BOLD, end='') # sys.stdout.flush() for i...
def getCountKwargs(func): """ Returns a list ["count kwarg", "count_max kwarg"] for a given function. Valid combinations are defined in `progress.validCountKwargs`. Returns None if no keyword arguments are found. """ # Get all arguments of the function if hasattr(func, "__code__"): func_args = func.__code__.co_varnames...
def humanize_speed(c_per_sec): """convert a speed in counts per second to counts per [s, min, h, d], choosing the smallest value greater zero. """ scales = [60, 60, 24] units = ['c/s', 'c/min', 'c/h', 'c/d'] speed = c_per_sec i = 0 if speed > 0: while (speed < 1) and (i < len(scales)): speed *= scales[i] i += 1 return ...
def humanize_time(secs): """convert second in to hh:mm:ss format """ if secs is None: return '--' if secs < 1: return "{:.2f}ms".format(secs*1000) elif secs < 10: return "{:.2f}s".format(secs) else: mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) return '{:02d}:{:02d}:{:02d}'.format(int(hours), int(mins), ...
def __cleanup(self): """ Wait at most twice as long as the given repetition interval for the _wrapper_function to terminate. If after that time the _wrapper_function has not terminated, send SIGTERM to and the process. Wait at most five times as long as the given repetition interval for the _wrapper_function to termina...
def start(self, timeout=None): """ uses multiprocess Process to call _wrapper_func in subprocess """ if self.is_alive(): log.warning("a process with pid %s is already running", self._proc.pid) return self._run.value = True self._func_running.value = False name = self.__class__.__name__ self.conn_recv, self.conn_send = ...
LoopExceptionError("the loop function return non zero exticode ({})!\n".format(exc)+ "see log (INFO level) for traceback information") time.sleep(0.1) if (timeout is not None) and ((time.time() - t0) > timeout): err_msg = "could not bring up function on time (timeout: {}s)".format(timeout) log.error(err_msg) log.info("...
def stop(self): """ stops the process triggered by start Setting the shared memory boolean run to false, which should prevent the loop from repeating. Call __cleanup to make sure the process stopped. After that we could trigger start() again. """ if self.is_alive(): self._proc.terminate() if self._proc is not None: sel...
def _calc(count, last_count, start_time, max_count, speed_calc_cycles, q, last_speed, lock): """do the pre calculations in order to get TET, speed, TTG :param count: count :param last_count: count at the last call, allows to treat the case of no progress between sequential calls :param start_time: the time when start w...
= 0, start_time_value last_count.value = count_value #last_old_count.value = old_count_value #last_old_time.value = old_time speed = (count_value - old_count_value) / (current_time - old_time) last_speed.value = speed else: # progress has not changed since last call # use also old (cached) data from the queue #old_coun...
def _reset_i(self, i): """ reset i-th progress information """ self.count[i].value=0 log.debug("reset counter %s", i) self.lock[i].acquire() for x in range(self.q[i].qsize()): self.q[i].get() self.lock[i].release() self.start_time[i].value = time.time()
def _show_stat(self): """ convenient functions to call the static show_stat_wrapper_multi with the given class members """ _show_stat_wrapper_multi_Progress(self.count, self.last_count, self.start_time, self.max_count, self.speed_calc_cycles, self.width, self.q, self.last_speed, self.prepend, self.show_stat, self.len, ...
def start(self): """ start """ # before printing any output to stout, we can now check this # variable to see if any other ProgressBar has reserved that # terminal. if (self.__class__.__name__ in terminal.TERMINAL_PRINT_LOOP_CLASSES): if not terminal.terminal_reserve(progress_obj=self): log.warning("tty already reserve...
def stop(self): """ trigger clean up by hand, needs to be done when not using context management via 'with' statement - will terminate loop process - show a last progress -> see the full 100% on exit - releases terminal reservation """ super(Progress, self).stop() terminal.terminal_unreserve(progress_obj=self, verbose=...
def _get_output_nodes(self, output_path, error_path): """ Extracts output nodes from the standard output and standard error files. """ from aiida.orm.data.array.trajectory import TrajectoryData import re state = None step = None scale = None with open(output_path) as f: lines = [x.strip('\n') for x in f.readlines()] re...
continue if state == 'nwchem-geometry-optimisation' and \ re.match('^\s*Output coordinates in a.u.',line): state = 'nwchem-geometry-optimisation-coordinates' result = re.match('scale by \s(*[\-\d\.]+)',line) scale = result.group(1) continue return [('parameters', ParameterData(dict=result_dict))]
def candidate_paths(self, filepath): """ Return candidates path for given path * If Filename does not starts with ``_``, will build a candidate for both with and without ``_`` prefix; * Will build For each available extensions if filename does not have an explicit extension; * Leading path directory is preserved; Args:...
filenames = [".".join([k, extension]) for k in filenames] # Else if no extension or not candidate, add candidate extensions else: # Restore uncandidate extensions if any if extension: filenames = [".".join([k, extension]) for k in filenames] new = [] for ext in self.CANDIDATE_EXTENSIONS: new.extend([".".join([k, ext]) ...
def check_candidate_exists(self, basepath, candidates): """ Check that at least one candidate exist into a directory. Args: basepath (str): Directory path where to search for candidate. candidates (list): List of candidate file paths. Returns: list: List of existing candidates. """ checked = [] for item in candidates: ...
def resolve(self, sourcepath, paths, library_paths=None): """ Resolve given paths from given base paths Return resolved path list. Note: Resolving strategy is made like libsass do, meaning paths in import rules are resolved from the source file where the import rules have been finded. If import rule is not explicit eno...
libraries to resolve paths if resolving fails on the base source path. Default to None. Raises: UnresolvablePath: If a path does not exist and ``STRICT_PATH_VALIDATION`` attribute is ``True``. Returns: list: List of resolved path. """ # Split basedir/filename from sourcepath, so the first resolving # basepath is the so...
Search all existing candidates: # * If more than one candidate raise an error; # * If only one, accept it; # * If no existing candidate raise an error; stack = [] for i, basepath in enumerate(basepaths): checked = self.check_candidate_exists(basepath, candidates) if checked: stack.extend(checked) # More than one existi...
def dump(self, content, filepath, indent=4): """ Dump settings content to filepath. Args: content (str): Settings content. filepath (str): Settings file location. """ with open(filepath, 'w') as fp: pyaml.dump(content, dst=fp, indent=indent)
def parse(self, filepath, content): """ Parse opened settings content using YAML parser. Args: filepath (str): Settings object, depends from backend content (str): Settings content from opened file, depends from backend. Raises: boussole.exceptions.SettingsBackendError: If parser can not decode a valid YAML object. Ret...
def filter_slaves(selfie, slaves): """ Remove slaves that are in an ODOWN or SDOWN state also remove slaves that do not have 'ok' master-link-status """ return [(s['ip'], s['port']) for s in slaves if not s['is_odown'] and not s['is_sdown'] and s['master-link-status'] == 'ok']
def get_message(zelf): """ get one message if available else return None if message is available returns the result of handler(message) does not block! if you would like to call your handler manually, this is the way to go. don't pass in a handler to Listener() and the default handler will log and return the message fo...
def listen(zelf): """ listen indefinitely, handling messages as they come all redis specific exceptions are handled, anything your handler raises will not be handled. setting active to False on the Listener object will gracefully stop the listen() function """ while zelf.active: try: msg = zelf.r.master.brpoplpush(zelf...
def run_op(self, op, sched): """ Handle the operation: * if coro is in STATE_RUNNING, send or throw the given op * if coro is in STATE_NEED_INIT, call the init function and if it doesn't return a generator, set STATE_COMPLETED and set the result to whatever the function returned. * if StopIteration is raised, set STATE...
(%s) should be less than %s!" % ( self, isinstance(op, CoroutineException) and op or (hasattr(op, 'state') and {0:'RUNNING', 1:'FINALIZED', 2:'ERRORED'}[op.state] or 'NOP'), op, self._state_names[self.state], self._state_names[self.STATE_COMPLETED] ) #~ assert self.state < self.STATE_COMPLETED, \ #~ "%s called with:%s,...
op is None self.coro = self.coro(*self.f_args, **self.f_kws) del self.f_args del self.f_kws if self._valid_gen(self.coro): self.state = self.STATE_RUNNING rop = None else: self.state = self.STATE_COMPLETED self.result = self.coro self.coro = None rop = self else: return None except StopIteration, e: self.state = self.S...
def render_field(field): """ 渲染字段验证代码 :param field: :type field: django.forms.Field :return: """ field = field.field if isinstance(field, forms.BoundField) else field validators = {} def no_compare_validator(): return not ('lessThan' in validators or 'greaterThan' in validators or 'between' in validators) if field.requ...
(fields.DecimalField, fields.FloatField)) and no_compare_validator(): validators['numeric'] = {} elif isinstance(field, fields.IntegerField) and no_compare_validator(): validators['integer'] = {} elif isinstance(field, (fields.DateField, fields.DateTimeField)): formats = field.input_formats if formats: validators['date...
def get_vcf_header(source): """Get the header lines of a vcf file Args: source(iterable): A vcf file Returns: head (HeaderParser): A headerparser object """ head = HeaderParser() #Parse the header lines for line in source: line = line.rstrip() if line.startswith('#'): if line.startswith('##'): logger.debug("Found metad...
def setup_config(command, filename, section, vars): """Place any commands to setup cogenircapp here""" conf = appconfig('config:' + filename) load_environment(conf.global_conf, conf.local_conf)
def _split_scheme(expression): """ Splits the scheme and actual expression :param str expression: The expression. :rtype: str """ match = re.search(r'^([a-z]+):(.*)$', expression) if not match: scheme = 'plain' actual = expression else: scheme = match.group(1) actual = match.group(2) return scheme, actual
def register_scheme(scheme, constructor): """ Registers a scheme. :param str scheme: The scheme. :param callable constructor: The SimpleCondition constructor. """ if not re.search(r'^[a-z]+$', scheme): raise ValueError('{0!s} is not a valid scheme'.format(scheme)) if scheme in SimpleConditionFactory._constructors: rais...
def _create(): """Globally called function for creating the isotope/element API.""" def creator(group): """Helper function applied to each symbol group of the raw isotope table.""" symbol = group['symbol'].values[0] try: # Ghosts and custom atoms don't necessarily have an abundance fraction mass = (group['mass']*group[...
def as_df(): """Return a dataframe of isotopes.""" records = [] for sym, ele in vars(_this).items(): if sym not in ["Element", "Isotope"] and not sym.startswith("_"): for k, v in vars(ele).items(): if k.startswith("_") and k[1].isdigit(): records.append({kk: vv for kk, vv in vars(v).items() if not kk.startswith("_")}) ...
def loadb(b): """Deserialize ``b`` (instance of ``bytes``) to a Python object.""" assert isinstance(b, (bytes, bytearray)) return std_json.loads(b.decode('utf-8'))