code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
type_1 = torch.device(requested_device) type_2 = torch.device(map_device) if type_1 != type_2: warnings.warn( 'Setting self.device = {} since the requested device ({}) ' 'is not available.'.format(map_device, requested_device), ...
def _check_device(self, requested_device, map_device)
Compare the requested device with the map device and return the map device if it differs from the requested device along with a warning.
4.338874
4.169586
1.040601
def _get_state_dict(f): map_location = get_map_location(self.device) self.device = self._check_device(self.device, map_location) return torch.load(f, map_location=map_location) # TODO: Remove warning in a future release if f is not None: ...
def load_params( self, f=None, f_params=None, f_optimizer=None, f_history=None, checkpoint=None)
Loads the the module's parameters, history, and optimizer, not the whole object. To save and load the whole object, use pickle. ``f_params`` and ``f_optimizer`` uses PyTorchs' :func:`~torch.save`. Parameters ---------- f_params : file-like object, str, None (de...
2.334778
2.331789
1.001282
# TODO: Remove warning in a future release warnings.warn( "save_history is deprecated and will be removed in the next " "release, please use save_params with the f_history keyword", DeprecationWarning) self.history.to_file(f)
def save_history(self, f)
Saves the history of ``NeuralNet`` as a json file. In order to use this feature, the history must only contain JSON encodable Python data structures. Numpy and PyTorch types should not be in the history. Parameters ---------- f : file-like object or str Examples...
6.298634
8.347901
0.754517
# TODO: Remove warning in a future release warnings.warn( "load_history is deprecated and will be removed in the next " "release, please use load_params with the f_history keyword", DeprecationWarning) self.history = History.from_file(f)
def load_history(self, f)
Load the history of a ``NeuralNet`` from a json file. See ``save_history`` for examples. Parameters ---------- f : file-like object or str
5.980223
6.732978
0.888199
if not isinstance(items, (tuple, list)): items = (items,) return all(item is not _none for item in items)
def _not_none(items)
Whether the item is a placeholder or contains a placeholder.
3.245176
3.046544
1.065199
type_ = list if isinstance(items, list) else tuple return type_(filter(_not_none, items))
def _filter_none(items)
Filter special placeholder value, preserves sequence type.
5.743152
4.042251
1.420781
if not isinstance(i, (tuple, list)): return item.get(i, _none) type_ = list if isinstance(item, list) else tuple return type_(item.get(j, _none) for j in i)
def _getitem(item, i)
Extract value or values from dicts. Covers the case of a single key or multiple keys. If not found, return placeholders instead.
3.965209
4.333483
0.915017
if len(i) > 4: raise KeyError( "Tried to index history with {} indices but only " "4 indices are possible.".format(len(i))) # fill trailing indices with None i_e, k_e, i_b, k_b = i + tuple([None] * (4 - len(i))) # handle special case of # history[j, 'batches', ...
def _unpack_index(i)
Unpack index and return exactly four elements. If index is more shallow than 4, return None for trailing dimensions. If index is deeper than 4, raise a KeyError.
4.512404
4.287669
1.052414
msg = "Call new_epoch before recording for the first time." if not self: raise ValueError(msg) self[-1][attr] = value
def record(self, attr, value)
Add a new value to the given column for the current epoch.
12.83569
10.193189
1.259242
with open_file_like(f, 'r') as fp: return cls(json.load(fp))
def from_file(cls, f)
Load the history of a ``NeuralNet`` from a json file. Parameters ---------- f : file-like object or str
6.020376
7.49873
0.802853
with open_file_like(f, 'w') as fp: json.dump(self.to_list(), fp)
def to_file(self, f)
Saves the history as a json file. In order to use this feature, the history must only contain JSON encodable Python data structures. Numpy and PyTorch types should not be in the history. Parameters ---------- f : file-like object or str
4.888474
5.723548
0.854098
if self.f_params is not None: f = self._format_target(net, self.f_params, -1) self._save_params(f, net, "f_params", "model parameters") if self.f_optimizer is not None: f = self._format_target(net, self.f_optimizer, -1) self._save_params(f, net, ...
def save_model(self, net)
Save the model. This function saves some or all of the following: - model parameters; - optimizer state; - training history; - entire model object.
2.592732
2.467669
1.05068
idx = -1 if ( self.event_name is not None and net.history ): for i, v in enumerate(net.history[:, self.event_name]): if v: idx = i return { "f_params": self._format_target(net, self.f_par...
def get_formatted_files(self, net)
Returns a dictionary of formatted filenames
4.317712
4.180024
1.032939
if f is None: return None if isinstance(f, str): f = self.fn_prefix + f.format( net=net, last_epoch=net.history[idx], last_batch=net.history[idx, 'batches', -1], ) return os.path.join(self.dirname, f...
def _format_target(self, net, f, idx)
Apply formatting to the target filename template.
5.036424
4.318329
1.16629
if not self.dirname: return def _is_truthy_and_not_str(f): return f and not isinstance(f, str) if ( _is_truthy_and_not_str(self.f_optimizer) or _is_truthy_and_not_str(self.f_params) or _is_truthy_and_not_str(self....
def _validate_filenames(self)
Checks if passed filenames are valid. Specifically, f_* parameter should not be passed in conjunction with dirname.
3.645323
3.21068
1.135374
if self.threshold_mode == 'rel': abs_threshold_change = self.threshold * score else: abs_threshold_change = self.threshold if self.lower_is_better: new_threshold = score - abs_threshold_change else: new_threshold = score + abs_thr...
def _calc_new_threshold(self, score)
Determine threshold based on score.
2.554547
2.423574
1.054041
if isinstance(h, Variable): return torch.tensor(h.data, device=h.device) else: return tuple(self.repackage_hidden(v) for v in h)
def repackage_hidden(self, h)
Wraps hidden states in new Variables, to detach them from their history.
2.76977
2.463508
1.12432
pat_1 = '__param_groups__(?P<group>[0-9])__(?P<name>.+)' pat_2 = '__(?!.*__.*)(?P<name>.+)' pat_1 = optimizer_name + pat_1 pat_2 = optimizer_name + pat_2 match_1 = re.compile(pat_1).fullmatch(param) match_2 = re.compile(pat_2).fullmatch(param) match = match_1 or match_2 if not mat...
def _extract_optimizer_param_name_and_group(optimizer_name, param)
Extract param group and param name from the given parameter name. Raises an error if the param name doesn't match one of - ``optimizer__param_groups__<group>__<name>`` - ``optimizer__<name>`` In the second case group defaults to 'all'. The second case explicitly forbids ``optimizer__foo__bar`` s...
2.765788
2.547176
1.085825
if param_group == 'all': groups = optimizer.param_groups else: groups = [optimizer.param_groups[int(param_group)]] for group in groups: group[param_name] = value
def _set_optimizer_param(optimizer, param_group, param_name, value)
Set a parameter on an all or a specific parameter group of an optimizer instance. To select all param groups, use ``param_group='all'``.
2.424498
2.045217
1.185448
if param == 'lr': param_group = 'all' param_name = 'lr' net.lr = value else: param_group, param_name = _extract_optimizer_param_name_and_group( optimizer_name, param) _set_optimizer_param( optimizer=getattr(net, optimizer_attr), param_group=p...
def optimizer_setter( net, param, value, optimizer_attr='optimizer_', optimizer_name='optimizer' )
Handle setting of optimizer parameters such as learning rate and parameter group specific parameters such as momentum. The parameters ``optimizer_attr`` and ``optimizer_name`` can be specified if there exists more than one optimizer (e.g., in seq2seq models).
2.902591
3.094859
0.937875
n = len(optimizer.param_groups) if not isinstance(lr, (list, tuple)): return lr * np.ones(n) if len(lr) != n: raise ValueError("{} lr values were passed for {} but there are " "{} param groups.".format(n, name, len(lr))) return np.array(lr)
def _check_lr(name, optimizer, lr)
Return one learning rate for each param group.
3.593222
3.217941
1.116622
test = torch.ones(1, requires_grad=True) opt = torch.optim.SGD([{'params': test, 'lr': initial_lr}]) policy_cls = self._get_policy_cls() sch = policy_cls(opt, **self.kwargs) if hasattr(sch, 'batch_step') and callable(sch.batch_step): step = sch.batch_step ...
def simulate(self, steps, initial_lr)
Simulates the learning rate scheduler. Parameters ---------- steps: int Number of steps to simulate initial_lr: float Initial learning rate Returns ------- lrs: numpy ndarray Simulated learning rates
3.243239
3.269955
0.99183
if policy not in [CyclicLR, ReduceLROnPlateau] and \ 'last_epoch' not in scheduler_kwargs: last_epoch = len(net.history) - 1 scheduler_kwargs['last_epoch'] = last_epoch if policy is CyclicLR and \ 'last_batch_idx' not in scheduler_kwargs: ...
def _get_scheduler(self, net, policy, **scheduler_kwargs)
Return scheduler, based on indicated policy, with appropriate parameters.
3.168036
3.083867
1.027293
if batch_idx is None: batch_idx = self.last_batch_idx + 1 self.last_batch_idx = batch_idx for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()): param_group['lr'] = lr
def batch_step(self, batch_idx=None)
Updates the learning rate for the batch index: ``batch_idx``. If ``batch_idx`` is None, ``CyclicLR`` will use an internal batch index to keep track of the index.
2.04365
1.831179
1.116029
cycle = np.floor(1 + self.last_batch_idx / self.total_size) x = 1 + self.last_batch_idx / self.total_size - cycle if x <= self.step_ratio: scale_factor = x / self.step_ratio else: scale_factor = (x-1)/(self.step_ratio-1) lrs = [] for base...
def get_lr(self)
Calculates the learning rate at batch index: ``self.last_batch_idx``.
2.169382
2.019764
1.074077
if self._verified is None: signature = self._data.get('Signature') if not signature: self._verified = False return self._verified # Decode the signature from base64 signature = bytes(base64.b64decode(signature)) ...
def is_verified(self)
Verifies an SES bounce message.
2.5329
2.440143
1.038013
if not hasattr(self, '_certificate'): cert_url = self._get_cert_url() # Only load certificates from a certain domain? # Without some kind of trusted domain check, any old joe could # craft a bounce message and sign it using his own certificate ...
def certificate(self)
Retrieves the certificate used to sign the bounce message. TODO: Cache the certificate based on the cert URL so we don't have to retrieve it for each bounce message. *We would need to do it in a secure way so that the cert couldn't be overwritten in the cache*
4.265606
3.857237
1.105871
cert_url = self._data.get('SigningCertURL') if cert_url: if cert_url.startswith('https://'): url_obj = urlparse(cert_url) for trusted_domain in settings.BOUNCE_CERT_DOMAINS: parts = trusted_domain.split('.') if ...
def _get_cert_url(self)
Get the signing certificate URL. Only accept urls that match the domains set in the AWS_SNS_BOUNCE_CERT_TRUSTED_DOMAINS setting. Sub-domains are allowed. i.e. if amazonaws.com is in the trusted domains then sns.us-east-1.amazonaws.com will match.
3.230548
2.71279
1.190858
# Depending on the message type the fields to add to the message # differ so we handle that here. msg_type = self._data.get('Type') if msg_type == 'Notification': fields_to_sign = [ 'Message', 'MessageId', 'Subject', ...
def _get_bytes_to_sign(self)
Creates the message used for signing SNS notifications. This is used to verify the bounce message when it is received.
2.805547
2.585187
1.08524
def _inner(request, *args, **kwargs): if not request.user.is_superuser: raise PermissionDenied return view_func(request, *args, **kwargs) return _inner
def superuser_only(view_func)
Limit a view to superuser only.
1.753556
1.747918
1.003226
result = stats_dict['GetSendStatisticsResponse']['GetSendStatisticsResult'] # Make a copy, so we don't change the original stats_dict. result = copy.deepcopy(result) datapoints = [] if localize: current_tz = localize.timezone(settings.TIME_ZONE) else: current_tz = None f...
def stats_to_list(stats_dict, localize=pytz)
Parse the output of ``SESConnection.get_send_statistics()`` in to an ordered list of 15-minute summaries.
2.841484
2.617361
1.085629
result = emails_dict['ListVerifiedEmailAddressesResponse'][ 'ListVerifiedEmailAddressesResult'] emails = [email for email in result['VerifiedEmailAddresses']] return sorted(emails)
def emails_parse(emails_dict)
Parse the output of ``SESConnection.list_verified_emails()`` and get a list of emails.
5.451558
4.26805
1.277295
t_bounces = 0 t_complaints = 0 t_delivery_attempts = 0 t_rejects = 0 for dp in stats_data: t_bounces += int(dp['Bounces']) t_complaints += int(dp['Complaints']) t_delivery_attempts += int(dp['DeliveryAttempts']) t_rejects += int(dp['Rejects']) return { ...
def sum_stats(stats_data)
Summarize the bounces, complaints, delivery attempts and rejects from a list of datapoints.
1.870176
1.495595
1.250457
cache_key = 'vhash:django_ses_stats' cached_view = cache.get(cache_key) if cached_view: return cached_view region = RegionInfo( name=settings.AWS_SES_REGION_NAME, endpoint=settings.AWS_SES_REGION_ENDPOINT) ses_conn = SESConnection( aws_access_key_id=settings.AC...
def dashboard(request)
Graph SES send statistics over time.
2.893756
2.791723
1.036549
try: import dkim except ImportError: pass else: if dkim_domain and dkim_key: sig = dkim.sign(message, dkim_selector, dkim_domain, dkim_key, include_headers...
def dkim_sign(message, dkim_domain=None, dkim_key=None, dkim_selector=None, dkim_headers=None)
Return signed email message if dkim package and settings are available.
2.467314
2.285025
1.079775
if self.connection: return False try: self.connection = SESConnection( aws_access_key_id=self._access_key_id, aws_secret_access_key=self._access_key, region=self._region, proxy=self._proxy, ...
def open(self)
Create a connection to the AWS API server. This can be reused for sending multiple emails.
2.427298
2.090189
1.161281
try: self.connection.close() self.connection = None except Exception: if not self.fail_silently: raise
def close(self)
Close any open HTTP connections to the API server.
4.31677
3.805064
1.13448
internal_assert(len(tokens) == 1, "invalid set maker tokens", tokens) if "comp" in tokens or "list" in tokens: return "(" + tokens[0] + ")" elif "test" in tokens: return "(" + tokens[0] + ",)" else: raise CoconutInternalException("invalid set maker item", tokens[0])
def set_to_tuple(tokens)
Converts set literal tokens to tuples.
5.48603
5.103516
1.074951
out = [] parts = path.split("./") # denotes from ... import ... if len(parts) == 1: imp_from, imp = None, parts[0] else: imp_from, imp = parts if imp == imp_as: imp_as = None elif imp.endswith("." + imp_as): if imp_from is None: imp_from = "" ...
def single_import(path, imp_as)
Generate import statements from a fully qualified import and the name to bind it to.
2.811859
2.745697
1.024096
importmap = [] # [((imp | old_imp, imp, version_check), imp_as), ...] for imps in imports: if len(imps) == 1: imp, imp_as = imps[0], imps[0] else: imp, imp_as = imps if imp_from is not None: imp = imp_from + "./" + imp # marker for from ... impo...
def universal_import(imports, imp_from=None, target="")
Generate code for a universal import of imports from imp_from on target. imports = [[imp1], [imp2, as], ...]
3.02626
2.962593
1.02149
req_args, def_args, star_arg, kwd_args, dubstar_arg = [], [], None, [], None pos = 0 for arg in tokens: if len(arg) == 1: if arg[0] == "*": # star sep (pos = 3) if pos >= 3: raise CoconutDeferredSyntaxError("star separator at inval...
def split_args_list(tokens, loc)
Splits function definition arguments.
2.195248
2.145556
1.02316
if len(tokens) == 2: matches, stmts = tokens cond = None elif len(tokens) == 3: matches, cond, stmts = tokens else: raise CoconutInternalException("invalid case match tokens", tokens) matching = Matcher(loc, check_var) matching.match(matches, match_to_var) if...
def match_case_tokens(loc, tokens, check_var, top)
Build code for matching the given case.
4.685908
4.475607
1.046988
if target is None: target = "" else: target = str(target).replace(".", "") if target in pseudo_targets: target = pseudo_targets[target] if target not in targets: raise CoconutException( "unsupported target Python ve...
def setup(self, target=None, strict=False, minify=False, line_numbers=False, keep_lines=False, no_tco=False)
Initializes parsing parameters.
4.092627
4.182549
0.9785
return hex(checksum( hash_sep.join( str(item) for item in (VERSION_STR,) + self.__reduce__()[1] + (package, code) ).encode(default_encoding), ))
def genhash(self, package, code)
Generate a hash from code.
11.961211
11.196692
1.068281
self.indchar = None self.comments = {} self.refs = [] self.set_skips([]) self.docstring = "" self.ichain_count = 0 self.tre_store_count = 0 self.case_check_count = 0 self.stmt_lambdas = [] if self.strict: self.unused_im...
def reset(self)
Resets references.
11.521624
10.734524
1.073324
skips.sort() internal_assert(lambda: len(set(skips)) == len(skips), "duplicate line skip(s) in skips", skips) self.skips = skips
def set_skips(self, skips)
Set the line skips.
7.517941
6.60323
1.138525
adj_ln = ln need_unskipped = 0 for i in self.skips: if i <= ln: need_unskipped += 1 elif adj_ln + need_unskipped < i: break else: need_unskipped -= i - adj_ln - 1 adj_ln = i retur...
def adjust(self, ln)
Converts a parsing line number into an original line number.
3.709216
3.509401
1.056937
if index is not None: return self.reformat(snip), len(self.reformat(snip[:index])) else: return self.repl_proc(snip, reformatting=True, log=False)
def reformat(self, snip, index=None)
Post process a preprocessed snippet.
6.991481
6.770233
1.03268
result = eval(self.reformat(code)) if result is None or isinstance(result, (bool, int, float, complex)): return repr(result) elif isinstance(result, bytes): return "b" + self.wrap_str_of(result) elif isinstance(result, str): return self.wrap_s...
def eval_now(self, code)
Reformat and evaluate a code snippet and return code for the result.
3.332405
3.011184
1.106676
if ln is None: ln = self.adjust(lineno(loc, original)) errstr, index = getline(loc, original), col(loc, original) - 1 if reformat: errstr, index = self.reformat(errstr, index) return errtype(message, errstr, index, ln, *args, **kwargs)
def make_err(self, errtype, message, original, loc, ln=None, reformat=True, *args, **kwargs)
Generate an error of the specified type.
4.4134
4.400061
1.003031
if self.strict: raise self.make_err(CoconutStyleError, *args, **kwargs) else: logger.warn_err(self.make_err(CoconutSyntaxWarning, *args, **kwargs))
def strict_err_or_warn(self, *args, **kwargs)
Raises an error if in strict mode, otherwise raises a warning.
4.912362
4.394649
1.117805
ref = (reftype, data) try: index = self.refs.index(ref) except ValueError: self.refs.append(ref) index = len(self.refs) - 1 return str(index)
def add_ref(self, reftype, data)
Add a reference and returns the identifier.
2.392895
2.121248
1.12806
try: got_reftype, data = self.refs[int(index)] except (IndexError, ValueError): raise CoconutInternalException("no reference at invalid index", index) internal_assert(got_reftype == reftype, "wanted " + reftype + " reference; got " + got_reftype + " reference") ...
def get_ref(self, reftype, index)
Retrieve a reference.
6.076068
6.116827
0.993337
if multiline: strchar *= 3 return strwrapper + self.add_ref("str", (text, strchar)) + unwrapper
def wrap_str(self, text, strchar, multiline=False)
Wrap a string.
19.25736
18.453348
1.04357
text_repr = ascii(text) internal_assert(text_repr[0] == text_repr[-1] and text_repr[0] in ("'", '"'), "cannot wrap str of", text) return self.wrap_str(text_repr[1:-1], text_repr[-1])
def wrap_str_of(self, text)
Wrap a string of a string.
4.734032
4.680169
1.011509
if not multiline: text = text.lstrip() if multiline: out = "\\" else: out = "\\\\" out += self.add_ref("passthrough", text) + unwrapper if not multiline: out += "\n" return out
def wrap_passthrough(self, text, multiline=True)
Wrap a passthrough.
6.281975
5.760526
1.090521
if reformat: text = self.reformat(text) return "#" + self.add_ref("comment", text) + unwrapper
def wrap_comment(self, text, reformat=True)
Wrap a comment.
10.533492
9.803022
1.074515
for get_proc in procs: proc = get_proc(self) inputstring = proc(inputstring, **kwargs) if log: logger.log_tag(proc.__name__, inputstring, multiline=True) return inputstring
def apply_procs(self, procs, kwargs, inputstring, log=True)
Apply processors to inputstring.
4.179206
4.179101
1.000025
out = self.apply_procs(self.preprocs, kwargs, str(inputstring)) logger.log_tag("skips", self.skips) return out
def pre(self, inputstring, **kwargs)
Perform pre-processing.
12.728317
12.416836
1.025085
internal_assert(isinstance(result, str), "got non-string parse result", result) return self.apply_procs(self.postprocs, kwargs, result)
def post(self, result, **kwargs)
Perform post-processing.
15.779699
14.658529
1.076486
header = getheader( which, use_hash=use_hash, target=self.target, no_tco=self.no_tco, strict=self.strict, ) if polish: header = self.polish(header) return header
def getheader(self, which, use_hash=None, polish=True)
Get a formatted header.
3.508208
3.558512
0.985864
msg, loc = err.args return self.make_err(CoconutSyntaxError, msg, original, loc)
def make_syntax_err(self, err, original)
Make a CoconutSyntaxError from a CoconutDeferredSyntaxError.
8.393142
4.802989
1.747483
err_line = err.line err_index = err.col - 1 err_lineno = err.lineno if include_ln else None if reformat: err_line, err_index = self.reformat(err_line, err_index) if err_lineno is not None: err_lineno = self.adjust(err_lineno) retur...
def make_parse_err(self, err, reformat=True, include_ln=True)
Make a CoconutParseError from a ParseBaseException.
2.854731
2.44043
1.169766
self.reset() pre_procd = None with logger.gather_parsing_stats(): try: pre_procd = self.pre(inputstring, **preargs) parsed = parse(parser, pre_procd) out = self.post(parsed, **postargs) except ParseBaseException as ...
def parse(self, inputstring, parser, preargs, postargs)
Use the parser to parse the inputstring with appropriate setup and teardown.
6.221777
6.1938
1.004517
if self.strict and nl_at_eof_check and inputstring and not inputstring.endswith("\n"): end_index = len(inputstring) - 1 if inputstring else 0 raise self.make_err(CoconutStyleError, "missing new line at end of file", inputstring, end_index) original_lines = inputstring.sp...
def prepare(self, inputstring, strip=False, nl_at_eof_check=False, **kwargs)
Prepare a string for processing.
3.267826
3.336435
0.979436
out = [] found = None # store of characters that might be the start of a passthrough hold = None # the contents of the passthrough so far count = None # current parenthetical level (num closes - num opens) multiline = None # if in a passthrough, is it a multiline pas...
def passthrough_proc(self, inputstring, **kwargs)
Process python passthroughs.
5.53532
5.465141
1.012841
count = 0 for i, c in enumerate(inputstring): if c == " ": count += 1 elif c == "\t": count += tabworth - (i % tabworth) else: break if self.indchar is None: self.indchar = c ...
def leading_whitespace(self, inputstring)
Count leading whitespace.
4.658706
4.316623
1.079248
lines = inputstring.splitlines() new = [] # new lines opens = [] # (line, col, adjusted ln) at which open parens were seen, newest first current = None # indentation level of previous line levels = [] # indentation levels of all previous blocks, newest at end ...
def ind_proc(self, inputstring, **kwargs)
Process indentation.
3.292898
3.273039
1.006068
regexes = [] for i in range(len(self.stmt_lambdas)): name = self.stmt_lambda_name(i) regex = compile_regex(r"\b%s\b" % (name,)) regexes.append(regex) out = [] for line in inputstring.splitlines(): for i, regex in enumerate(regexes)...
def stmt_lambda_proc(self, inputstring, **kwargs)
Add statement lambda definitions.
2.727743
2.679658
1.017944
out = [] level = 0 for line in inputstring.splitlines(): line, comment = split_comment(line.strip()) indent, line = split_leading_indent(line) level += ind_change(indent) if line: line = " " * self.tabideal * level + lin...
def reind_proc(self, inputstring, **kwargs)
Add back indentation.
5.264238
4.784388
1.100295
if self.keep_lines: if not 1 <= ln <= len(self.original_lines) + 1: raise CoconutInternalException( "out of bounds line number", ln, "not in range [1, " + str(len(self.original_lines) + 1) + "]", ) elif ln =...
def ln_comment(self, ln)
Get an end line comment. CoconutInternalExceptions should always be caught and complained.
2.539501
2.399441
1.058372
out = [] ln = 1 # line number for line in inputstring.splitlines(): add_one_to_ln = False try: if line.endswith(lnwrapper): line, index = line[:-1].rsplit("#", 1) new_ln = self.get_ref("ln", index) ...
def endline_repl(self, inputstring, reformatting=False, **kwargs)
Add end of line comments.
3.963507
3.79408
1.044656
out = [] index = None for c in append_it(inputstring, None): try: if index is not None: if c is not None and c in nums: index += c elif c == unwrapper and index: ref = se...
def passthrough_repl(self, inputstring, **kwargs)
Add back passthroughs.
4.15897
4.055928
1.025405
out = [] comment = None string = None for i, c in enumerate(append_it(inputstring, None)): try: if comment is not None: if c is not None and c in nums: comment += c elif c == unwrapper ...
def str_repl(self, inputstring, **kwargs)
Add back strings.
3.1446
3.090271
1.017581
return self.apply_procs(self.replprocs, kwargs, inputstring, log=log)
def repl_proc(self, inputstring, log=True, **kwargs)
Process using replprocs.
9.521475
6.77591
1.405195
pre_header = self.getheader(initial, use_hash=use_hash, polish=False) main_header = self.getheader(header, polish=False) if self.minify: main_header = minify(main_header) return pre_header + self.docstring + main_header + inputstring
def header_proc(self, inputstring, header="file", initial="initial", use_hash=None, **kwargs)
Add the header.
4.269791
4.057997
1.052192
internal_assert(len(tokens) == 2, "invalid docstring tokens", tokens) self.docstring = self.reformat(tokens[0]) + "\n\n" return tokens[1]
def set_docstring(self, loc, tokens)
Set the docstring.
6.022133
5.540574
1.086915
internal_assert(len(tokens) == 1, "invalid yield from tokens", tokens) if self.target_info < (3, 3): return ( yield_from_var + " = " + tokens[0] + "\nfor " + yield_item_var + " in " + yield_from_var + ":\n" + openindent + "yield " + yi...
def yield_from_handle(self, tokens)
Process Python 3.3 yield from.
4.698357
4.297672
1.093233
internal_assert(len(tokens) == 1, "invalid endline tokens", tokens) lines = tokens[0].splitlines(True) if self.minify: lines = lines[0] out = [] ln = lineno(loc, original) for endline in lines: out.append(self.wrap_line_number(self.adjust(...
def endline_handle(self, original, loc, tokens)
Add line number information to end of line.
5.169368
5.042144
1.025232
internal_assert(len(tokens) == 1, "invalid comment tokens", tokens) ln = self.adjust(lineno(loc, original)) internal_assert(lambda: ln not in self.comments, "multiple comments on line", ln) self.comments[ln] = tokens[0] return ""
def comment_handle(self, original, loc, tokens)
Store comment in comments.
5.825058
5.689538
1.023819
internal_assert(len(tokens) == 3, "invalid assignment tokens", tokens) name, op, item = tokens out = "" if op == "|>=": out += name + " = (" + item + ")(" + name + ")" elif op == "|*>=": out += name + " = (" + item + ")(*" + name + ")" eli...
def augassign_handle(self, tokens)
Process assignments.
2.659963
2.640449
1.00739
if len(tokens) == 0: if self.target.startswith("3"): return "" else: return "(_coconut.object)" elif len(tokens) == 1 and len(tokens[0]) == 1: if "tests" in tokens[0]: if self.strict and tokens[0][0] == "(object...
def classlist_handle(self, original, loc, tokens)
Process class inheritance lists.
4.534604
4.499173
1.007875
if len(tokens) == 1: imp_from, imports = None, tokens[0] elif len(tokens) == 2: imp_from, imports = tokens if imp_from == "__future__": self.strict_err_or_warn("unnecessary from __future__ import (Coconut does these automatically)", original, ...
def import_handle(self, original, loc, tokens)
Universalizes imports.
5.139069
4.829713
1.064053
internal_assert(len(tokens) == 2, "invalid raise from tokens", tokens) if self.target.startswith("3"): return "raise " + tokens[0] + " from " + tokens[1] else: return ( raise_from_var + " = " + tokens[0] + "\n" + raise_from_var + "...
def complex_raise_stmt_handle(self, tokens)
Process Python 3 raise from statement.
3.703384
3.351564
1.104972
internal_assert(len(tokens) == 3, "invalid dictionary comprehension tokens", tokens) if self.target.startswith("3"): key, val, comp = tokens return "{" + key + ": " + val + " " + comp + "}" else: key, val, comp = tokens return "dict(((" + ...
def dict_comp_handle(self, loc, tokens)
Process Python 2.7 dictionary comprehension.
4.783344
4.471815
1.069665
base_line = clean(self.reformat(getline(loc, original))) line_wrap = self.wrap_str_of(base_line) repr_wrap = self.wrap_str_of(ascii(base_line)) return ( "if not " + check_var + ":\n" + openindent + match_err_var + ' = _coconut_MatchError("pattern-matching...
def pattern_error(self, original, loc, value_var, check_var)
Construct a pattern-matching error message.
5.024037
4.895434
1.02627
internal_assert(len(tokens) == 2, "invalid destructuring assignment tokens", tokens) matches, item = tokens out = match_handle(loc, [matches, "in", item, None]) out += self.pattern_error(original, loc, match_to_var, match_check_var) return out
def destructuring_stmt_handle(self, original, loc, tokens)
Process match assign blocks.
11.210786
10.221052
1.096833
if len(tokens) == 2: func, matches = tokens cond = None elif len(tokens) == 3: func, matches, cond = tokens else: raise CoconutInternalException("invalid match function definition tokens", tokens) matcher = Matcher(loc, match_check...
def name_match_funcdef_handle(self, original, loc, tokens)
Process match defs. Result must be passed to insert_docstring_handle.
4.437995
4.367546
1.01613
if len(tokens) == 3: func, args = get_infix_items(tokens) cond = None elif len(tokens) == 4: func, args = get_infix_items(tokens[:-1]) cond = tokens[-1] else: raise CoconutInternalException("invalid infix match function definit...
def op_match_funcdef_handle(self, original, loc, tokens)
Process infix match defs. Result must be passed to insert_docstring_handle.
3.059742
2.802392
1.091832
internal_assert(len(tokens) == 1 and len(tokens[0]) == 1, "invalid set literal tokens", tokens) if self.target_info < (2, 7): return "_coconut.set(" + set_to_tuple(tokens[0]) + ")" else: return "{" + tokens[0][0] + "}"
def set_literal_handle(self, tokens)
Converts set literals to the right form for the target Python.
5.37905
4.459843
1.206107
if len(tokens) == 1: set_type = tokens[0] if set_type == "s": return "_coconut.set()" elif set_type == "f": return "_coconut.frozenset()" else: raise CoconutInternalException("invalid set type", set_type) ...
def set_letter_literal_handle(self, tokens)
Process set literals.
2.385719
2.310863
1.032393
internal_assert(1 <= len(tokens) <= 3, "invalid exec statement tokens", tokens) if self.target.startswith("2"): out = "exec " + tokens[0] if len(tokens) > 1: out += " in " + ", ".join(tokens[1:]) return out else: return "ex...
def exec_stmt_handle(self, tokens)
Process Python-3-style exec statements.
4.567284
4.099064
1.114226
if index is None: index = len(self.stmt_lambdas) return stmt_lambda_var + "_" + str(index)
def stmt_lambda_name(self, index=None)
Return the next (or specified) statement lambda name.
4.81399
4.913484
0.979751
if len(tokens) == 2: params, stmts = tokens elif len(tokens) == 3: params, stmts, last = tokens if "tests" in tokens: stmts = stmts.asList() + ["return " + last] else: stmts = stmts.asList() + [last] else: ...
def stmt_lambdef_handle(self, original, loc, tokens)
Process multi-line lambdef statements.
4.749019
4.739746
1.001956
try: yield except ParseBaseException as err: complain(self.make_parse_err(err, reformat=False, include_ln=False)) except CoconutException as err: complain(err)
def complain_on_err(self)
Complain about any parsing-related errors raised inside.
8.235945
6.697801
1.229649
try: first_line, rest_of_lines = block.split("\n", 1) except ValueError: pass else: raw_first_line = split_leading_trailing_indent(rem_comment(first_line))[1] if match_in(self.just_a_string, raw_first_line): return first_li...
def split_docstring(self, block)
Split a code block into a docstring and a body.
5.010229
4.970552
1.007982
def tre_return_handle(loc, tokens): internal_assert(len(tokens) == 1, "invalid tail recursion elimination tokens", tokens) args = tokens[0][1:-1] # strip parens # check if there is anything in the arguments that will store a reference # to the current sc...
def tre_return(self, func_name, func_args, func_store, use_mock=True)
Generate grammar element that matches a string which is just a TRE return statement.
4.51577
4.389309
1.028811
lines = [] # transformed lines tco = False # whether tco was done tre = False # whether tre was done level = 0 # indentation level disabled_until_level = None # whether inside of a disabled block attempt_tre = tre_return_grammar is not None # whether to eve...
def transform_returns(self, raw_lines, tre_return_grammar=None, use_mock=None, is_async=False)
Apply TCO, TRE, or async universalization to the given function.
4.231359
4.098351
1.032454
if len(tokens) == 1: decorators, funcdef = "", tokens[0] elif len(tokens) == 2: decorators, funcdef = tokens else: raise CoconutInternalException("invalid function definition tokens", tokens) # extract information about the function r...
def decoratable_funcdef_stmt_handle(self, original, loc, tokens, is_async=False)
Determines if TCO or TRE can be done and if so does it, handles dotted function names, and universalizes async functions.
4.138689
4.011025
1.031828
internal_assert(len(tokens) == 1, "invalid await statement tokens", tokens) if not self.target: self.make_err( CoconutTargetError, "await requires a specific target", original, loc, target="sys", ) e...
def await_item_handle(self, original, loc, tokens)
Check for Python 3.5 await expression.
5.761008
5.361364
1.074542