text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_key(bytes_, encoding, keynames='curtsies', full=False):
"""Return key pressed from bytes_ or None
Return a key name or None meaning it's an incomplete sequence of bytes
(more bytes needed to determine the key pressed)
encoding is how the bytes should be translated to unicode - it should
match the terminal encoding.
keynames is a string describing how keys should be named:
* curtsies uses unicode strings like <F8>
* curses uses unicode strings similar to those returned by
the Python ncurses window.getkey function, like KEY_F(8),
plus a nonstandard representation of meta keys (bytes 128-255)
because returning the corresponding unicode code point would be
indistinguishable from the multibyte sequence that encodes that
character in the current encoding
* bytes returns the original bytes from stdin (NOT unicode)
if full, match a key even if it could be a prefix to another key
(useful for detecting a plain escape key for instance, since
escape is also a prefix to a bunch of char sequences for other keys)
Events are subclasses of Event, or unicode strings
Precondition: get_key(prefix, keynames) is None for all proper prefixes of
bytes. This means get_key should be called on progressively larger inputs
(for 'asdf', first on 'a', then on 'as', then on 'asd' - until a non-None
value is returned)
"""
if not all(isinstance(c, type(b'')) for c in bytes_):
raise ValueError("get key expects bytes, got %r" % bytes_) # expects raw bytes
if keynames not in ['curtsies', 'curses', 'bytes']:
raise ValueError("keynames must be one of 'curtsies', 'curses' or 'bytes'")
seq = b''.join(bytes_)
if len(seq) > MAX_KEYPRESS_SIZE:
raise ValueError('unable to decode bytes %r' % seq)
def key_name():
if keynames == 'curses':
if seq in CURSES_NAMES: # may not be here (and still not decodable) curses names incomplete
return CURSES_NAMES[seq]
# Otherwise, there's no special curses name for this
try:
return seq.decode(encoding) # for normal decodable text or a special curtsies sequence with bytes that can be decoded
except UnicodeDecodeError:
# this sequence can't be decoded with this encoding, so we need to represent the bytes
if len(seq) == 1:
return u'x%02X' % ord(seq)
#TODO figure out a better thing to return here
else:
raise NotImplementedError("are multibyte unnameable sequences possible?")
return u'bytes: ' + u'-'.join(u'x%02X' % ord(seq[i:i+1]) for i in range(len(seq)))
#TODO if this isn't possible, return multiple meta keys as a paste event if paste events enabled
elif keynames == 'curtsies':
if seq in CURTSIES_NAMES:
return CURTSIES_NAMES[seq]
return seq.decode(encoding) #assumes that curtsies names are a subset of curses ones
else:
assert keynames == 'bytes'
return seq
key_known = seq in CURTSIES_NAMES or seq in CURSES_NAMES or decodable(seq, encoding)
if full and key_known:
return key_name()
elif seq in KEYMAP_PREFIXES or could_be_unfinished_char(seq, encoding):
return None # need more input to make up a full keypress
elif key_known:
return key_name()
else:
seq.decode(encoding) # this will raise a unicode error (they're annoying to raise ourselves)
assert False, 'should have raised an unicode decode error' | [
"def",
"get_key",
"(",
"bytes_",
",",
"encoding",
",",
"keynames",
"=",
"'curtsies'",
",",
"full",
"=",
"False",
")",
":",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"c",
",",
"type",
"(",
"b''",
")",
")",
"for",
"c",
"in",
"bytes_",
")",
":",
"... | 46.805195 | 27.844156 |
def creep_kill(self, target, timestamp):
"""
A creep was tragically killed. Need to split this into radiant/dire
and neutrals
"""
self.creep_kill_types[target] += 1
matched = False
for k, v in self.creep_types.iteritems():
if target.startswith(k):
matched = True
setattr(self, v, getattr(self, v) + 1)
break
if not matched:
print('> unhandled creep type'.format(target)) | [
"def",
"creep_kill",
"(",
"self",
",",
"target",
",",
"timestamp",
")",
":",
"self",
".",
"creep_kill_types",
"[",
"target",
"]",
"+=",
"1",
"matched",
"=",
"False",
"for",
"k",
",",
"v",
"in",
"self",
".",
"creep_types",
".",
"iteritems",
"(",
")",
... | 30.8125 | 15.3125 |
def embed(contents='', width='100%', height=512, *args, **kwargs):
"""
Embed geojson.io in an iframe in Jupyter/IPython notebook.
Parameters
----------
contents - see make_url()
width - string, default '100%' - width of the iframe
height - string / int, default 512 - height of the iframe
kwargs - additional arguments are passed to `make_url()`
"""
from IPython.display import HTML
url = make_url(contents, *args, **kwargs)
html = '<iframe src={url} width={width} height={height}></iframe>'.format(
url=url, width=width, height=height)
return HTML(html) | [
"def",
"embed",
"(",
"contents",
"=",
"''",
",",
"width",
"=",
"'100%'",
",",
"height",
"=",
"512",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"HTML",
"url",
"=",
"make_url",
"(",
"contents",
"... | 33.333333 | 19.888889 |
def create_constant(self, expression, *, verbose=True):
"""Append a constant to the stored list.
Parameters
----------
expression : str
Expression for the new constant.
verbose : boolean (optional)
Toggle talkback. Default is True
See Also
--------
set_constants
Remove and replace all constants.
remove_constant
Remove an individual constant.
"""
if expression in self.constant_expressions:
wt_exceptions.ObjectExistsWarning.warn(expression)
return self.constants[self.constant_expressions.index(expression)]
constant = Constant(self, expression)
if constant.units is None:
constant.convert(constant.variables[0].units)
self._constants.append(constant)
self.flush()
self._on_constants_updated()
if verbose:
print("Constant '{}' added".format(constant.expression))
return constant | [
"def",
"create_constant",
"(",
"self",
",",
"expression",
",",
"*",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"expression",
"in",
"self",
".",
"constant_expressions",
":",
"wt_exceptions",
".",
"ObjectExistsWarning",
".",
"warn",
"(",
"expression",
")",
"... | 34.689655 | 15 |
def parse(self, obj):
"""
Parse the object's properties according to its default types.
"""
for k, default in obj.__class__.defaults.items():
typ = type(default)
if typ is str:
continue
v = getattr(obj, k)
if typ is int:
setattr(obj, k, int(v or default))
elif typ is float:
setattr(obj, k, float(v or default))
elif typ is bool:
setattr(obj, k, bool(int(v or default))) | [
"def",
"parse",
"(",
"self",
",",
"obj",
")",
":",
"for",
"k",
",",
"default",
"in",
"obj",
".",
"__class__",
".",
"defaults",
".",
"items",
"(",
")",
":",
"typ",
"=",
"type",
"(",
"default",
")",
"if",
"typ",
"is",
"str",
":",
"continue",
"v",
... | 34.933333 | 12.4 |
def attempt_squash_merge(pr: PullRequestDetails
) -> Union[bool, CannotAutomergeError]:
"""
References:
https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
"""
url = ("https://api.github.com/repos/{}/{}/pulls/{}/merge"
"?access_token={}".format(pr.repo.organization,
pr.repo.name,
pr.pull_id,
pr.repo.access_token))
data = {
'commit_title': '{} (#{})'.format(pr.title, pr.pull_id),
'commit_message': pr.body,
'sha': pr.branch_sha,
'merge_method': 'squash'
}
response = requests.put(url, json=data)
if response.status_code == 200:
# Merge succeeded.
log('Merged PR#{} ({!r}):\n{}\n'.format(
pr.pull_id,
pr.title,
indent(pr.body)))
return True
if response.status_code == 405:
return CannotAutomergeError("Pull Request is not mergeable.")
if response.status_code == 409:
# Need to sync.
return False
raise RuntimeError('Merge failed. Code: {}. Content: {}.'.format(
response.status_code, response.content)) | [
"def",
"attempt_squash_merge",
"(",
"pr",
":",
"PullRequestDetails",
")",
"->",
"Union",
"[",
"bool",
",",
"CannotAutomergeError",
"]",
":",
"url",
"=",
"(",
"\"https://api.github.com/repos/{}/{}/pulls/{}/merge\"",
"\"?access_token={}\"",
".",
"format",
"(",
"pr",
"."... | 33.777778 | 18.222222 |
def exists(*nictag, **kwargs):
'''
Check if nictags exists
nictag : string
one or more nictags to check
verbose : boolean
return list of nictags
CLI Example:
.. code-block:: bash
salt '*' nictagadm.exists admin
'''
ret = {}
if not nictag:
return {'Error': 'Please provide at least one nictag to check.'}
cmd = 'nictagadm exists -l {0}'.format(' '.join(nictag))
res = __salt__['cmd.run_all'](cmd)
if not kwargs.get('verbose', False):
ret = res['retcode'] == 0
else:
missing = res['stderr'].splitlines()
for nt in nictag:
ret[nt] = nt not in missing
return ret | [
"def",
"exists",
"(",
"*",
"nictag",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"nictag",
":",
"return",
"{",
"'Error'",
":",
"'Please provide at least one nictag to check.'",
"}",
"cmd",
"=",
"'nictagadm exists -l {0}'",
".",
"for... | 22 | 21.733333 |
def t_php_CLOSE_TAG(t):
r'[?%]>\r?\n?'
t.lexer.lineno += t.value.count("\n")
t.lexer.begin('INITIAL')
return t | [
"def",
"t_php_CLOSE_TAG",
"(",
"t",
")",
":",
"t",
".",
"lexer",
".",
"lineno",
"+=",
"t",
".",
"value",
".",
"count",
"(",
"\"\\n\"",
")",
"t",
".",
"lexer",
".",
"begin",
"(",
"'INITIAL'",
")",
"return",
"t"
] | 24.4 | 16 |
def validate_pair(ob: Any) -> bool:
"""
Does the object have length 2?
"""
try:
if len(ob) != 2:
log.warning("Unexpected result: {!r}", ob)
raise ValueError()
except ValueError:
return False
return True | [
"def",
"validate_pair",
"(",
"ob",
":",
"Any",
")",
"->",
"bool",
":",
"try",
":",
"if",
"len",
"(",
"ob",
")",
"!=",
"2",
":",
"log",
".",
"warning",
"(",
"\"Unexpected result: {!r}\"",
",",
"ob",
")",
"raise",
"ValueError",
"(",
")",
"except",
"Val... | 23.272727 | 13.272727 |
def no_crop(im, min_sz=None, interpolation=cv2.INTER_AREA):
""" Return a squared resized image """
r,c,*_ = im.shape
if min_sz is None: min_sz = min(r,c)
return cv2.resize(im, (min_sz, min_sz), interpolation=interpolation) | [
"def",
"no_crop",
"(",
"im",
",",
"min_sz",
"=",
"None",
",",
"interpolation",
"=",
"cv2",
".",
"INTER_AREA",
")",
":",
"r",
",",
"c",
",",
"",
"*",
"_",
"=",
"im",
".",
"shape",
"if",
"min_sz",
"is",
"None",
":",
"min_sz",
"=",
"min",
"(",
"r"... | 46.8 | 14 |
def filter(self, query: Query):
"""Return a new filtered query.
Use the tree to filter the query and return a new query "filtered".
This query can be filtered again using another tree or even a manual
filter.
To manually filter query see :
- https://docs.sqlalchemy.org/en/rel_1_2/orm/query.html?highlight=filter#sqlalchemy.orm.query.Query.filter
"""
entity = query.column_descriptions[0]['type']
new_query, filters = self._root.filter(query, entity)
return new_query.filter(filters) | [
"def",
"filter",
"(",
"self",
",",
"query",
":",
"Query",
")",
":",
"entity",
"=",
"query",
".",
"column_descriptions",
"[",
"0",
"]",
"[",
"'type'",
"]",
"new_query",
",",
"filters",
"=",
"self",
".",
"_root",
".",
"filter",
"(",
"query",
",",
"enti... | 46.833333 | 20.666667 |
def shell_comment(c):
'Do not shell-escape raw strings in comments, but do handle line breaks.'
return ShellQuoted('# {c}').format(c=ShellQuoted(
(raw_shell(c) if isinstance(c, ShellQuoted) else c)
.replace('\n', '\n# ')
)) | [
"def",
"shell_comment",
"(",
"c",
")",
":",
"return",
"ShellQuoted",
"(",
"'# {c}'",
")",
".",
"format",
"(",
"c",
"=",
"ShellQuoted",
"(",
"(",
"raw_shell",
"(",
"c",
")",
"if",
"isinstance",
"(",
"c",
",",
"ShellQuoted",
")",
"else",
"c",
")",
".",... | 41.666667 | 21.333333 |
def _ewp_flags_set(self, ewp_dic_subset, project_dic, flag_type, flag_dic):
""" Flags from misc to set to ewp project """
try:
if flag_type in project_dic['misc'].keys():
# enable commands
index_option = self._get_option(ewp_dic_subset, flag_dic['enable'])
self._set_option(ewp_dic_subset[index_option], '1')
index_option = self._get_option(ewp_dic_subset, flag_dic['set'])
if type(ewp_dic_subset[index_option]['state']) != list:
# if it's string, only one state
previous_state = ewp_dic_subset[index_option]['state']
ewp_dic_subset[index_option]['state'] = []
ewp_dic_subset[index_option]['state'].append(previous_state)
for item in project_dic['misc'][flag_type]:
ewp_dic_subset[index_option]['state'].append(item)
except KeyError:
return | [
"def",
"_ewp_flags_set",
"(",
"self",
",",
"ewp_dic_subset",
",",
"project_dic",
",",
"flag_type",
",",
"flag_dic",
")",
":",
"try",
":",
"if",
"flag_type",
"in",
"project_dic",
"[",
"'misc'",
"]",
".",
"keys",
"(",
")",
":",
"# enable commands",
"index_opti... | 50.947368 | 26.368421 |
def is_back_tracking(neurite):
''' Check if a neurite process backtracks to a previous node. Back-tracking takes place
when a daughter of a branching process goes back and either overlaps with a previous point, or
lies inside the cylindrical volume of the latter.
Args:
neurite(Neurite): neurite to operate on
Returns:
True Under the following scenaria:
1. A segment endpoint falls back and overlaps with a previous segment's point
2. The geometry of a segment overlaps with a previous one in the section
'''
def pair(segs):
''' Pairs the input list into triplets'''
return zip(segs, segs[1:])
def coords(node):
''' Returns the first three values of the tree that correspond to the x, y, z coordinates'''
return node[COLS.XYZ]
def max_radius(seg):
''' Returns maximum radius from the two segment endpoints'''
return max(seg[0][COLS.R], seg[1][COLS.R])
def is_not_zero_seg(seg):
''' Returns True if segment has zero length'''
return not np.allclose(coords(seg[0]), coords(seg[1]))
def is_in_the_same_verse(seg1, seg2):
''' Checks if the vectors face the same direction. This
is true if their dot product is greater than zero.
'''
v1 = coords(seg2[1]) - coords(seg2[0])
v2 = coords(seg1[1]) - coords(seg1[0])
return np.dot(v1, v2) >= 0
def is_seg2_within_seg1_radius(dist, seg1, seg2):
''' Checks whether the orthogonal distance from the point at the end of
seg1 to seg2 segment body is smaller than the sum of their radii
'''
return dist <= max_radius(seg1) + max_radius(seg2)
def is_seg1_overlapping_with_seg2(seg1, seg2):
'''Checks if a segment is in proximity of another one upstream'''
# get the coordinates of seg2 (from the origin)
s1 = coords(seg2[0])
s2 = coords(seg2[1])
# vector of the center of seg2 (from the origin)
C = 0.5 * (s1 + s2)
# endpoint of seg1 (from the origin)
P = coords(seg1[1])
# vector from the center C of seg2 to the endpoint P of seg1
CP = P - C
# vector of seg2
S1S2 = s2 - s1
# projection of CP upon seg2
prj = mm.vector_projection(CP, S1S2)
# check if the distance of the orthogonal complement of CP projection on S1S2
# (vertical distance from P to seg2) is smaller than the sum of the radii. (overlap)
# If not exit early, because there is no way that backtracking can feasible
if not is_seg2_within_seg1_radius(np.linalg.norm(CP - prj), seg1, seg2):
return False
# projection lies within the length of the cylinder. Check if the distance between
# the center C of seg2 and the projection of the end point of seg1, P is smaller than
# half of the others length plus a 5% tolerance
return np.linalg.norm(prj) < 0.55 * np.linalg.norm(S1S2)
def is_inside_cylinder(seg1, seg2):
''' Checks if seg2 approximately lies within a cylindrical volume of seg1.
Two conditions must be satisfied:
1. The two segments are not facing the same direction (seg2 comes back to seg1)
2. seg2 is overlaping with seg1
'''
return not is_in_the_same_verse(seg1, seg2) and is_seg1_overlapping_with_seg2(seg1, seg2)
# filter out single segment sections
section_itr = (snode for snode in neurite.iter_sections() if snode.points.shape[0] > 2)
for snode in section_itr:
# group each section's points intro triplets
segment_pairs = list(filter(is_not_zero_seg, pair(snode.points)))
# filter out zero length segments
for i, seg1 in enumerate(segment_pairs[1:]):
# check if the end point of the segment lies within the previous
# ones in the current sectionmake
for seg2 in segment_pairs[0: i + 1]:
if is_inside_cylinder(seg1, seg2):
return True
return False | [
"def",
"is_back_tracking",
"(",
"neurite",
")",
":",
"def",
"pair",
"(",
"segs",
")",
":",
"''' Pairs the input list into triplets'''",
"return",
"zip",
"(",
"segs",
",",
"segs",
"[",
"1",
":",
"]",
")",
"def",
"coords",
"(",
"node",
")",
":",
"''' Returns... | 41.113402 | 25.237113 |
def set_temperature(self, zone, temperature, until=None):
"""Sets the temperature of the given zone."""
if until is None:
data = {"Value": temperature, "Status": "Hold", "NextTime": None}
else:
data = {"Value": temperature,
"Status": "Temporary",
"NextTime": until.strftime('%Y-%m-%dT%H:%M:%SZ')}
self._set_heat_setpoint(zone, data) | [
"def",
"set_temperature",
"(",
"self",
",",
"zone",
",",
"temperature",
",",
"until",
"=",
"None",
")",
":",
"if",
"until",
"is",
"None",
":",
"data",
"=",
"{",
"\"Value\"",
":",
"temperature",
",",
"\"Status\"",
":",
"\"Hold\"",
",",
"\"NextTime\"",
":"... | 42 | 17.1 |
def get_stream_when_active(stream_name, region=None, key=None, keyid=None, profile=None):
'''
Get complete stream info from AWS, returning only when the stream is in the ACTIVE state.
Continues to retry when stream is updating or creating.
If the stream is deleted during retries, the loop will catch the error and break.
CLI example::
salt myminion boto_kinesis.get_stream_when_active my_stream region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
stream_status = None
# only get basic stream until it's active,
# so we don't pull the full list of shards repeatedly (in case of very large stream)
attempt = 0
max_retry_delay = 10
while stream_status != "ACTIVE":
time.sleep(_jittered_backoff(attempt, max_retry_delay))
attempt += 1
stream_response = _get_basic_stream(stream_name, conn)
if 'error' in stream_response:
return stream_response
stream_status = stream_response['result']["StreamDescription"]["StreamStatus"]
# now it's active, get the full stream if necessary
if stream_response['result']["StreamDescription"]["HasMoreShards"]:
stream_response = _get_full_stream(stream_name, region, key, keyid, profile)
return stream_response | [
"def",
"get_stream_when_active",
"(",
"stream_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
... | 42.9 | 29.033333 |
def bf(items, targets, **kwargs):
"""Best-Fit
Complexity O(n^2)
"""
bins = [(target, []) for target in targets]
skip = []
for item in items:
containers = []
capacities = []
for target, content in bins:
capacity = target - sum(content)
if item <= capacity:
containers.append(content)
capacities.append(capacity - item)
if len(capacities):
weighted = zip(containers, weight(capacities, **kwargs))
content, _ = min(weighted, key=operator.itemgetter(1))
content.append(item)
else:
skip.append(item)
return bins, skip | [
"def",
"bf",
"(",
"items",
",",
"targets",
",",
"*",
"*",
"kwargs",
")",
":",
"bins",
"=",
"[",
"(",
"target",
",",
"[",
"]",
")",
"for",
"target",
"in",
"targets",
"]",
"skip",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"containers",
"=... | 27.666667 | 16.333333 |
def analyze(self, text):
"""Return the sentiment as a tuple of the form:
``(polarity, subjectivity)``
:param str text: A string.
.. todo::
Figure out best format to be passed to the analyzer.
There might be a better format than a string of space separated
lemmas (e.g. with pos tags) but the parsing/tagging
results look rather inaccurate and a wrong pos
might prevent the lexicon lookup of an otherwise correctly
lemmatized word form (or would it not?) - further checks needed.
"""
if self.lemmatize:
text = self._lemmatize(text)
return self.RETURN_TYPE(*pattern_sentiment(text)) | [
"def",
"analyze",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"lemmatize",
":",
"text",
"=",
"self",
".",
"_lemmatize",
"(",
"text",
")",
"return",
"self",
".",
"RETURN_TYPE",
"(",
"*",
"pattern_sentiment",
"(",
"text",
")",
")"
] | 37.157895 | 21.368421 |
def _parse_source_sections(self, diff_str):
"""
Given the output of `git diff`, return a dictionary
with keys that are source file paths.
Each value is a list of lines from the `git diff` output
related to the source file.
Raises a `GitDiffError` if `diff_str` is in an invalid format.
"""
# Create a dict to map source files to lines in the diff output
source_dict = dict()
# Keep track of the current source file
src_path = None
# Signal that we've found a hunk (after starting a source file)
found_hunk = False
# Parse the diff string into sections by source file
for line in diff_str.split('\n'):
# If the line starts with "diff --git"
# or "diff --cc" (in the case of a merge conflict)
# then it is the start of a new source file
if line.startswith('diff --git') or line.startswith('diff --cc'):
# Retrieve the name of the source file
src_path = self._parse_source_line(line)
# Create an entry for the source file, if we don't
# already have one.
if src_path not in source_dict:
source_dict[src_path] = []
# Signal that we're waiting for a hunk for this source file
found_hunk = False
# Every other line is stored in the dictionary for this source file
# once we find a hunk section
else:
# Only add lines if we're in a hunk section
# (ignore index and files changed lines)
if found_hunk or line.startswith('@@'):
# Remember that we found a hunk
found_hunk = True
if src_path is not None:
source_dict[src_path].append(line)
else:
# We tolerate other information before we have
# a source file defined, unless it's a hunk line
if line.startswith("@@"):
msg = "Hunk has no source file: '{}'".format(line)
raise GitDiffError(msg)
return source_dict | [
"def",
"_parse_source_sections",
"(",
"self",
",",
"diff_str",
")",
":",
"# Create a dict to map source files to lines in the diff output",
"source_dict",
"=",
"dict",
"(",
")",
"# Keep track of the current source file",
"src_path",
"=",
"None",
"# Signal that we've found a hunk ... | 36.557377 | 22.229508 |
def _cmd_create(self):
"""Create a migration in the current or new revision folder
"""
assert self._message, "need to supply a message for the \"create\" command"
if not self._revisions:
self._revisions.append("1")
# get the migration folder
rev_folder = self._revisions[-1]
full_rev_path = os.path.join(self._migration_path, rev_folder)
if not os.path.exists(full_rev_path):
os.mkdir(full_rev_path)
else:
count = len(glob.glob(os.path.join(full_rev_path, "*")))
# create next revision folder if needed
if count and self._rev and int(self._rev) == 0:
rev_folder = str(int(rev_folder) + 1)
full_rev_path = os.path.join(self._migration_path, rev_folder)
os.mkdir(full_rev_path)
self._revisions.append(rev_folder)
# format file name
filename = '_'.join([s.lower() for s in self._message.split(' ') if s.strip()])
for p in string.punctuation:
if p in filename:
filename = filename.replace(p, '_')
filename = "%s_%s" % (datetime.utcnow().strftime("%Y%m%d%H%M%S"), filename.replace('__', '_'))
# create the migration files
self._log(0, "creating files: ")
for s in ('up', 'down'):
file_path = os.path.join(full_rev_path, "%s.%s.sql" % (filename, s))
with open(file_path, 'a+') as w:
w.write('\n'.join([
'-- *** %s ***' % s.upper(),
'-- file: %s' % os.path.join(rev_folder, filename),
'-- comment: %s' % self._message]))
self._log(0, file_path) | [
"def",
"_cmd_create",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_message",
",",
"\"need to supply a message for the \\\"create\\\" command\"",
"if",
"not",
"self",
".",
"_revisions",
":",
"self",
".",
"_revisions",
".",
"append",
"(",
"\"1\"",
")",
"# get the... | 44.710526 | 17.078947 |
def get_template_substitution_values(self, value):
"""
Return value-related substitutions.
"""
return {
'initial': os.path.basename(conditional_escape(value)),
'initial_url': conditional_escape(value.url),
} | [
"def",
"get_template_substitution_values",
"(",
"self",
",",
"value",
")",
":",
"return",
"{",
"'initial'",
":",
"os",
".",
"path",
".",
"basename",
"(",
"conditional_escape",
"(",
"value",
")",
")",
",",
"'initial_url'",
":",
"conditional_escape",
"(",
"value... | 33 | 14 |
def focus_loss(labels, probs, loss, gamma):
"""
Calculate the alpha balanced focal loss.
See the focal loss paper: "Focal Loss for Dense Object Detection" [by Facebook AI Research]
:param labels: A float tensor of shape [batch_size, ..., num_classes] representing the label class probabilities.
:param probs: A float tensor of shape [batch_size, ..., num_classes] representing the probs (after softmax).
:param loss: A float tensor of shape [batch_size, ...] representing the loss that should be focused.
:param gamma: The focus parameter.
:return: A tensor representing the weighted cross entropy.
"""
with tf.variable_scope("focus_loss"):
# Compute p_t that is used in paper.
# FIXME is it possible that the 1-p term does not make any sense?
p_t = tf.reduce_sum(probs * labels, axis=-1)# + tf.reduce_sum((1.0 - probs) * (1.0 - labels), axis=-1)
focal_factor = tf.pow(1.0 - p_t, gamma) if gamma > 0 else 1 # Improve stability for gamma = 0
return tf.stop_gradient(focal_factor) * loss | [
"def",
"focus_loss",
"(",
"labels",
",",
"probs",
",",
"loss",
",",
"gamma",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"focus_loss\"",
")",
":",
"# Compute p_t that is used in paper.",
"# FIXME is it possible that the 1-p term does not make any sense?",
"p_t",... | 55.315789 | 31.631579 |
def store_env(path=None):
'''Encode current environment as yaml and store in path or a temporary
file. Return the path to the stored environment.
'''
path = path or get_store_env_tmp()
env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False)
with open(path, 'w') as f:
f.write(env_dict)
return path | [
"def",
"store_env",
"(",
"path",
"=",
"None",
")",
":",
"path",
"=",
"path",
"or",
"get_store_env_tmp",
"(",
")",
"env_dict",
"=",
"yaml",
".",
"safe_dump",
"(",
"os",
".",
"environ",
".",
"data",
",",
"default_flow_style",
"=",
"False",
")",
"with",
"... | 26 | 26 |
def init_loopback(self, data):
"""Just initialize the object for our Pseudo Loopback"""
self.name = data["name"]
self.description = data['description']
self.win_index = data['win_index']
self.mac = data["mac"]
self.guid = data["guid"]
self.ip = "127.0.0.1" | [
"def",
"init_loopback",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"name",
"=",
"data",
"[",
"\"name\"",
"]",
"self",
".",
"description",
"=",
"data",
"[",
"'description'",
"]",
"self",
".",
"win_index",
"=",
"data",
"[",
"'win_index'",
"]",
"sel... | 38.125 | 6.875 |
def get_next(self, tag="<"):
"""
This function is tricky and took me a while to figure out.
The tag specifies the direction where the current edge came from.
tag ntag
---> V >----> U
cur next
This means the next vertex should follow the outs since this tag is
inward '<'. Check if there are multiple branches if len(L) == 1, and
also check if the next it finds has multiple incoming edges though if
len(B) == 1.
"""
next, ntag = None, None
L = self.outs if tag == "<" else self.ins
if len(L) == 1:
e, = L
if e.v1.v == self.v:
next, ntag = e.v2, e.o2
ntag = "<" if ntag == ">" else ">" # Flip tag if on other end
else:
next, ntag = e.v1, e.o1
if next: # Validate the next vertex
B = next.ins if ntag == "<" else next.outs
if len(B) > 1:
return None, None
return next, ntag | [
"def",
"get_next",
"(",
"self",
",",
"tag",
"=",
"\"<\"",
")",
":",
"next",
",",
"ntag",
"=",
"None",
",",
"None",
"L",
"=",
"self",
".",
"outs",
"if",
"tag",
"==",
"\"<\"",
"else",
"self",
".",
"ins",
"if",
"len",
"(",
"L",
")",
"==",
"1",
"... | 30.757576 | 21.545455 |
def decode(self, code, terminator='\0'):
r"""Return a word decoded from BWT form.
Parameters
----------
code : str
The word to transform from BWT form
terminator : str
A character added to signal the end of the string
Returns
-------
str
Word decoded by BWT
Raises
------
ValueError
Specified terminator absent from code.
Examples
--------
>>> bwt = BWT()
>>> bwt.decode('n\x00ilag')
'align'
>>> bwt.decode('annb\x00aa')
'banana'
>>> bwt.decode('annb@aa', '@')
'banana'
"""
if code:
if terminator not in code:
raise ValueError(
'Specified terminator, {}, absent from code.'.format(
terminator if terminator != '\0' else '\\0'
)
)
else:
wordlist = [''] * len(code)
for i in range(len(code)):
wordlist = sorted(
code[i] + wordlist[i] for i in range(len(code))
)
rows = [w for w in wordlist if w[-1] == terminator][0]
return rows.rstrip(terminator)
else:
return '' | [
"def",
"decode",
"(",
"self",
",",
"code",
",",
"terminator",
"=",
"'\\0'",
")",
":",
"if",
"code",
":",
"if",
"terminator",
"not",
"in",
"code",
":",
"raise",
"ValueError",
"(",
"'Specified terminator, {}, absent from code.'",
".",
"format",
"(",
"terminator"... | 27.3125 | 19.333333 |
def new_logger(name):
'''Return new logger which will log both to logstash and to file in JSON
format.
Log files are stored in <logdir>/name.json
'''
log = get_task_logger(name)
handler = logstash.LogstashHandler(
config.logstash.host, config.logstash.port)
log.addHandler(handler)
create_logdir(config.logdir)
handler = TimedRotatingFileHandler(
'%s.json' % join(config.logdir, name),
when='midnight',
utc=True,
)
handler.setFormatter(JSONFormatter())
log.addHandler(handler)
return TaskCtxAdapter(log, {}) | [
"def",
"new_logger",
"(",
"name",
")",
":",
"log",
"=",
"get_task_logger",
"(",
"name",
")",
"handler",
"=",
"logstash",
".",
"LogstashHandler",
"(",
"config",
".",
"logstash",
".",
"host",
",",
"config",
".",
"logstash",
".",
"port",
")",
"log",
".",
... | 24.956522 | 20.26087 |
def leaves(self, prefix=None):
"""
LIKE items() BUT RECURSIVE, AND ONLY FOR THE LEAVES (non dict) VALUES
"""
prefix = coalesce(prefix, "")
output = []
for k, v in self.items():
if _get(v, CLASS) in data_types:
output.extend(wrap(v).leaves(prefix=prefix + literal_field(k) + "."))
else:
output.append((prefix + literal_field(k), v))
return output | [
"def",
"leaves",
"(",
"self",
",",
"prefix",
"=",
"None",
")",
":",
"prefix",
"=",
"coalesce",
"(",
"prefix",
",",
"\"\"",
")",
"output",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"_get",
"(",
"v",
... | 37.166667 | 15.833333 |
def update_counter(self, key, value, **kwargs):
"""
Updates the value of a counter stored in this bucket. Positive
values increment the counter, negative values decrement. See
:meth:`RiakClient.update_counter()
<riak.client.RiakClient.update_counter>` for options.
.. deprecated:: 2.1.0 (Riak 2.0) Riak 1.4-style counters are
deprecated in favor of the :class:`~riak.datatypes.Counter`
datatype.
:param key: the key of the counter
:type key: string
:param value: the amount to increment or decrement
:type value: integer
"""
return self._client.update_counter(self, key, value, **kwargs) | [
"def",
"update_counter",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_client",
".",
"update_counter",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | 40.647059 | 19 |
def create_ambiente(self):
"""Get an instance of ambiente services facade."""
return Ambiente(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_ambiente",
"(",
"self",
")",
":",
"return",
"Ambiente",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | 30.714286 | 11.857143 |
def strike(channel, nick, rest):
"Strike last <n> statements from the record"
yield NoLog
rest = rest.strip()
if not rest:
count = 1
else:
if not rest.isdigit():
yield "Strike how many? Argument must be a positive integer."
raise StopIteration
count = int(rest)
try:
struck = Logger.store.strike(channel, nick, count)
tmpl = (
"Isn't undo great? Last %d statement%s "
"by %s were stricken from the record."
)
yield tmpl % (struck, 's' if struck > 1 else '', nick)
except Exception:
traceback.print_exc()
yield "Hmm.. I didn't find anything of yours to strike!" | [
"def",
"strike",
"(",
"channel",
",",
"nick",
",",
"rest",
")",
":",
"yield",
"NoLog",
"rest",
"=",
"rest",
".",
"strip",
"(",
")",
"if",
"not",
"rest",
":",
"count",
"=",
"1",
"else",
":",
"if",
"not",
"rest",
".",
"isdigit",
"(",
")",
":",
"y... | 27.571429 | 20.142857 |
def raw_cap(self, refresh=False):
"""
Raw xml(cap) of the the feed. If a valid cache is available
it is used, else a new copy of the feed is grabbed
Note: you can force refresh here, if you do, don't also manually call refresh
"""
if refresh is True:
self._raw = self.refresh()
if self._raw is None:
self._raw = self._get_feed_cache()
if self._raw is None:
self._raw = self.refresh()
return self._raw | [
"def",
"raw_cap",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
"is",
"True",
":",
"self",
".",
"_raw",
"=",
"self",
".",
"refresh",
"(",
")",
"if",
"self",
".",
"_raw",
"is",
"None",
":",
"self",
".",
"_raw",
"=",
"self",... | 38.153846 | 12.153846 |
def event_transition(self, event_cls, event_type, ion_type, value):
"""Returns an ion event event_transition that yields to another co-routine."""
annotations = self.annotations or ()
depth = self.depth
whence = self.whence
if ion_type is IonType.SYMBOL:
if not annotations and depth == 0 and isinstance(value, _IVMToken):
event = value.ivm_event()
if event is None:
_illegal_character(None, self, 'Illegal IVM: %s.' % (value.text,))
return Transition(event, whence)
assert not isinstance(value, _IVMToken)
return Transition(
event_cls(event_type, ion_type, value, self.field_name, annotations, depth),
whence
) | [
"def",
"event_transition",
"(",
"self",
",",
"event_cls",
",",
"event_type",
",",
"ion_type",
",",
"value",
")",
":",
"annotations",
"=",
"self",
".",
"annotations",
"or",
"(",
")",
"depth",
"=",
"self",
".",
"depth",
"whence",
"=",
"self",
".",
"whence"... | 42.666667 | 20.333333 |
def generate_make_string(out_f, max_step):
"""Generate the make_string template"""
steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)]
with Namespace(
out_f,
['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl']
) as nsp:
generate_take(out_f, steps, nsp.prefix())
out_f.write(
'{0}template <int LenNow, int LenRemaining, char... Cs>\n'
'{0}struct make_string;\n'
'\n'
'{0}template <char... Cs>'
' struct make_string<0, 0, Cs...> : string<> {{}};\n'
.format(nsp.prefix())
)
disable_sun = False
for i in reversed(steps):
if i > 64 and not disable_sun:
out_f.write('#ifndef __SUNPRO_CC\n')
disable_sun = True
out_f.write(
'{0}template <int LenRemaining,{1}char... Cs>'
' struct make_string<{2},LenRemaining,{3}Cs...> :'
' concat<string<{4}>,'
' typename make_string<take(LenRemaining),'
'LenRemaining-take(LenRemaining),Cs...>::type> {{}};\n'
.format(
nsp.prefix(),
''.join('char {0},'.format(n) for n in unique_names(i)),
i,
''.join('{0},'.format(n) for n in unique_names(i)),
','.join(unique_names(i))
)
)
if disable_sun:
out_f.write('#endif\n') | [
"def",
"generate_make_string",
"(",
"out_f",
",",
"max_step",
")",
":",
"steps",
"=",
"[",
"2",
"**",
"n",
"for",
"n",
"in",
"xrange",
"(",
"int",
"(",
"math",
".",
"log",
"(",
"max_step",
",",
"2",
")",
")",
",",
"-",
"1",
",",
"-",
"1",
")",
... | 36.75 | 18.525 |
def _tf_squared_euclidean(X, Y):
"""Squared Euclidean distance between the rows of `X` and `Y`.
"""
return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1) | [
"def",
"_tf_squared_euclidean",
"(",
"X",
",",
"Y",
")",
":",
"return",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"pow",
"(",
"tf",
".",
"subtract",
"(",
"X",
",",
"Y",
")",
",",
"2",
")",
",",
"axis",
"=",
"1",
")"
] | 44.75 | 8.5 |
def service_group_exists(name,
groupname=None,
vsys=1,
members=None,
description=None,
commit=False):
'''
Ensures that a service group object exists in the configured state. If it does not exist or is not configured with
the specified attributes, it will be adjusted to match the specified values.
This module will enforce group membership. If a group exists and contains members this state does not include,
those members will be removed and replaced with the specified members in the state.
name: The name of the module function to execute.
groupname(str): The name of the service group object. The name is case-sensitive and can have up to 31 characters,
which an be letters, numbers, spaces, hyphens, and underscores. The name must be unique on a firewall and, on
Panorama, unique within its device group and any ancestor or descendant device groups.
vsys(str): The string representation of the VSYS ID. Defaults to VSYS 1.
members(str, list): The members of the service group. These must be valid service objects or service groups on the
system that already exist prior to the execution of this state.
description(str): A description for the policy (up to 255 characters).
commit(bool): If true the firewall will commit the changes, if false do not commit changes.
SLS Example:
.. code-block:: yaml
panos/service-group/my-group:
panos.service_group_exists:
- groupname: my-group
- vsys: 1
- members:
- tcp-80
- custom-port-group
- description: A group that needs to exist
- commit: False
'''
ret = _default_ret(name)
if not groupname:
ret.update({'comment': "The group name field must be provided."})
return ret
# Check if service group object currently exists
group = __salt__['panos.get_service_group'](groupname, vsys)['result']
if group and 'entry' in group:
group = group['entry']
else:
group = {}
# Verify the arguments
if members:
element = "<members>{0}</members>".format(_build_members(members, True))
else:
ret.update({'comment': "The group members must be provided."})
return ret
if description:
element += "<description>{0}</description>".format(description)
full_element = "<entry name='{0}'>{1}</entry>".format(groupname, element)
new_group = xml.to_dict(ET.fromstring(full_element), True)
if group == new_group:
ret.update({
'comment': 'Service group object already exists. No changes required.',
'result': True
})
return ret
else:
xpath = "/config/devices/entry[@name=\'localhost.localdomain\']/vsys/entry[@name=\'vsys{0}\']/service-group/" \
"entry[@name=\'{1}\']".format(vsys, groupname)
result, msg = _edit_config(xpath, full_element)
if not result:
ret.update({
'comment': msg
})
return ret
if commit is True:
ret.update({
'changes': {'before': group, 'after': new_group},
'commit': __salt__['panos.commit'](),
'comment': 'Service group object successfully configured.',
'result': True
})
else:
ret.update({
'changes': {'before': group, 'after': new_group},
'comment': 'Service group object successfully configured.',
'result': True
})
return ret | [
"def",
"service_group_exists",
"(",
"name",
",",
"groupname",
"=",
"None",
",",
"vsys",
"=",
"1",
",",
"members",
"=",
"None",
",",
"description",
"=",
"None",
",",
"commit",
"=",
"False",
")",
":",
"ret",
"=",
"_default_ret",
"(",
"name",
")",
"if",
... | 34.567308 | 28.759615 |
def phenotypes(institute_id, case_name, phenotype_id=None):
"""Handle phenotypes."""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
case_url = url_for('.case', institute_id=institute_id, case_name=case_name)
is_group = request.args.get('is_group') == 'yes'
user_obj = store.user(current_user.email)
if phenotype_id:
# DELETE a phenotype item/group from case
store.remove_phenotype(institute_obj, case_obj, user_obj, case_url,
phenotype_id, is_group=is_group)
else:
try:
# add a new phenotype item/group to the case
phenotype_term = request.form['hpo_term']
if phenotype_term.startswith('HP:') or len(phenotype_term) == 7:
hpo_term = phenotype_term.split(' | ', 1)[0]
store.add_phenotype(institute_obj, case_obj, user_obj, case_url,
hpo_term=hpo_term, is_group=is_group)
else:
# assume omim id
store.add_phenotype(institute_obj, case_obj, user_obj, case_url,
omim_term=phenotype_term)
except ValueError:
return abort(400, ("unable to add phenotype: {}".format(phenotype_term)))
return redirect(case_url) | [
"def",
"phenotypes",
"(",
"institute_id",
",",
"case_name",
",",
"phenotype_id",
"=",
"None",
")",
":",
"institute_obj",
",",
"case_obj",
"=",
"institute_and_case",
"(",
"store",
",",
"institute_id",
",",
"case_name",
")",
"case_url",
"=",
"url_for",
"(",
"'.c... | 49.961538 | 23.884615 |
def use_model(self, model_name):
"""
Decide whether to use a model, based on the model name and the lists of
models to exclude and include.
"""
# Check against exclude list.
if self.exclude_models:
for model_pattern in self.exclude_models:
model_pattern = '^%s$' % model_pattern.replace('*', '.*')
if re.search(model_pattern, model_name):
return False
# Check against exclude list.
elif self.include_models:
for model_pattern in self.include_models:
model_pattern = '^%s$' % model_pattern.replace('*', '.*')
if re.search(model_pattern, model_name):
return True
# Return `True` if `include_models` is falsey, otherwise return `False`.
return not self.include_models | [
"def",
"use_model",
"(",
"self",
",",
"model_name",
")",
":",
"# Check against exclude list.",
"if",
"self",
".",
"exclude_models",
":",
"for",
"model_pattern",
"in",
"self",
".",
"exclude_models",
":",
"model_pattern",
"=",
"'^%s$'",
"%",
"model_pattern",
".",
... | 44.947368 | 13.368421 |
def scenario_risk(riskinputs, riskmodel, param, monitor):
"""
Core function for a scenario computation.
:param riskinput:
a of :class:`openquake.risklib.riskinput.RiskInput` object
:param riskmodel:
a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance
:param param:
dictionary of extra parameters
:param monitor:
:class:`openquake.baselib.performance.Monitor` instance
:returns:
a dictionary {
'agg': array of shape (E, L, R, 2),
'avg': list of tuples (lt_idx, rlz_idx, asset_ordinal, statistics)
}
where E is the number of simulated events, L the number of loss types,
R the number of realizations and statistics is an array of shape
(n, R, 4), with n the number of assets in the current riskinput object
"""
E = param['E']
L = len(riskmodel.loss_types)
result = dict(agg=numpy.zeros((E, L), F32), avg=[],
all_losses=AccumDict(accum={}))
for ri in riskinputs:
for out in riskmodel.gen_outputs(ri, monitor, param['epspath']):
r = out.rlzi
weight = param['weights'][r]
slc = param['event_slice'](r)
for l, loss_type in enumerate(riskmodel.loss_types):
losses = out[loss_type]
if numpy.product(losses.shape) == 0: # happens for all NaNs
continue
stats = numpy.zeros(len(ri.assets), stat_dt) # mean, stddev
for a, asset in enumerate(ri.assets):
stats['mean'][a] = losses[a].mean()
stats['stddev'][a] = losses[a].std(ddof=1)
result['avg'].append((l, r, asset['ordinal'], stats[a]))
agglosses = losses.sum(axis=0) # shape num_gmfs
result['agg'][slc, l] += agglosses * weight
if param['asset_loss_table']:
aids = ri.assets['ordinal']
result['all_losses'][l, r] += AccumDict(zip(aids, losses))
return result | [
"def",
"scenario_risk",
"(",
"riskinputs",
",",
"riskmodel",
",",
"param",
",",
"monitor",
")",
":",
"E",
"=",
"param",
"[",
"'E'",
"]",
"L",
"=",
"len",
"(",
"riskmodel",
".",
"loss_types",
")",
"result",
"=",
"dict",
"(",
"agg",
"=",
"numpy",
".",
... | 44.911111 | 19.533333 |
def add_context(self, context, label=None):
"""Append `context` to model
Arguments:
context (dict): Serialised to add
Schema:
context.json
"""
assert isinstance(context, dict)
item = defaults["common"].copy()
item.update(defaults["instance"])
item.update(context)
item["family"] = None
item["label"] = context["data"].get("label") or settings.ContextLabel
item["itemType"] = "instance"
item["isToggled"] = True
item["optional"] = False
item["hasCompatible"] = True
item = self.add_item(item)
self.instances.append(item) | [
"def",
"add_context",
"(",
"self",
",",
"context",
",",
"label",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"context",
",",
"dict",
")",
"item",
"=",
"defaults",
"[",
"\"common\"",
"]",
".",
"copy",
"(",
")",
"item",
".",
"update",
"(",
"def... | 25.115385 | 17.153846 |
def dict(cls):
""" Return a dict containing all of the configuration properties
:returns: (dict) containing all configuration properties.
"""
if cls._properties is None:
cls._readStdConfigFiles()
# Make a copy so we can update any current values obtained from environment
# variables
result = dict(cls._properties)
keys = os.environ.keys()
replaceKeys = filter(lambda x: x.startswith(cls.envPropPrefix),
keys)
for envKey in replaceKeys:
key = envKey[len(cls.envPropPrefix):]
key = key.replace('_', '.')
result[key] = os.environ[envKey]
return result | [
"def",
"dict",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_properties",
"is",
"None",
":",
"cls",
".",
"_readStdConfigFiles",
"(",
")",
"# Make a copy so we can update any current values obtained from environment",
"# variables",
"result",
"=",
"dict",
"(",
"cls",
".... | 29.857143 | 18.47619 |
def bp_to_aap (bp):
"""Converts a basepol into a tuple of (ant1, ant2, pol)."""
ap1, ap2 = bp
if ap1 < 0:
raise ValueError ('first antpol %d is negative' % ap1)
if ap2 < 0:
raise ValueError ('second antpol %d is negative' % ap2)
pol = _fpol_to_pol[((ap1 & 0x7) << 4) + (ap2 & 0x7)]
if pol == 0xFF:
raise ValueError ('no CASA polarization code for pairing '
'%c-%c' % (fpol_names[ap1 & 0x7],
fpol_names[ap2 & 0x7]))
return ap1 >> 3, ap2 >> 3, pol | [
"def",
"bp_to_aap",
"(",
"bp",
")",
":",
"ap1",
",",
"ap2",
"=",
"bp",
"if",
"ap1",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'first antpol %d is negative'",
"%",
"ap1",
")",
"if",
"ap2",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'second antpol %d is... | 34.25 | 22.9375 |
def prepare_refresh_token_request(self, token_url, refresh_token=None,
body='', scope=None, **kwargs):
"""Prepare an access token refresh request.
Expired access tokens can be replaced by new access tokens without
going through the OAuth dance if the client obtained a refresh token.
This refresh token and authentication credentials can be used to
obtain a new access token, and possibly a new refresh token.
:param token_url: Provider token refresh endpoint URL.
:param refresh_token: Refresh token string.
:param body: Existing request body (URL encoded string) to embed parameters
into. This may contain extra paramters. Default ''.
:param scope: List of scopes to request. Must be equal to
or a subset of the scopes granted when obtaining the refresh
token.
:param kwargs: Additional parameters to included in the request.
:returns: The prepared request tuple with (url, headers, body).
"""
if not is_secure_transport(token_url):
raise InsecureTransportError()
self.scope = scope or self.scope
body = self.prepare_refresh_body(body=body,
refresh_token=refresh_token, scope=self.scope, **kwargs)
return token_url, FORM_ENC_HEADERS, body | [
"def",
"prepare_refresh_token_request",
"(",
"self",
",",
"token_url",
",",
"refresh_token",
"=",
"None",
",",
"body",
"=",
"''",
",",
"scope",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_secure_transport",
"(",
"token_url",
")",
":",
... | 44.322581 | 27.225806 |
def make_repository_component(self):
"""Return an XML string representing this BMI in a workflow.
This description is required by EMELI to discover and load models.
Returns
-------
xml : str
String serialized XML representation of the component in the
model repository.
"""
component = etree.Element('component')
comp_name = etree.Element('comp_name')
comp_name.text = self.model.name
component.append(comp_name)
mod_path = etree.Element('module_path')
mod_path.text = os.getcwd()
component.append(mod_path)
mod_name = etree.Element('module_name')
mod_name.text = self.model.name
component.append(mod_name)
class_name = etree.Element('class_name')
class_name.text = 'model_class'
component.append(class_name)
model_name = etree.Element('model_name')
model_name.text = self.model.name
component.append(model_name)
lang = etree.Element('language')
lang.text = 'python'
component.append(lang)
ver = etree.Element('version')
ver.text = self.get_attribute('version')
component.append(ver)
au = etree.Element('author')
au.text = self.get_attribute('author_name')
component.append(au)
hu = etree.Element('help_url')
hu.text = 'http://github.com/sorgerlab/indra'
component.append(hu)
for tag in ('cfg_template', 'time_step_type', 'time_units',
'grid_type', 'description', 'comp_type', 'uses_types'):
elem = etree.Element(tag)
elem.text = tag
component.append(elem)
return etree.tounicode(component, pretty_print=True) | [
"def",
"make_repository_component",
"(",
"self",
")",
":",
"component",
"=",
"etree",
".",
"Element",
"(",
"'component'",
")",
"comp_name",
"=",
"etree",
".",
"Element",
"(",
"'comp_name'",
")",
"comp_name",
".",
"text",
"=",
"self",
".",
"model",
".",
"na... | 30.982143 | 16.964286 |
def create_new_folder(self, current_path, title, subtitle, is_package):
"""Create new folder"""
if current_path is None:
current_path = ''
if osp.isfile(current_path):
current_path = osp.dirname(current_path)
name, valid = QInputDialog.getText(self, title, subtitle,
QLineEdit.Normal, "")
if valid:
dirname = osp.join(current_path, to_text_string(name))
try:
os.mkdir(dirname)
except EnvironmentError as error:
QMessageBox.critical(self, title,
_("<b>Unable "
"to create folder <i>%s</i></b>"
"<br><br>Error message:<br>%s"
) % (dirname, to_text_string(error)))
finally:
if is_package:
fname = osp.join(dirname, '__init__.py')
try:
with open(fname, 'wb') as f:
f.write(to_binary_string('#'))
return dirname
except EnvironmentError as error:
QMessageBox.critical(self, title,
_("<b>Unable "
"to create file <i>%s</i></b>"
"<br><br>Error message:<br>%s"
) % (fname,
to_text_string(error))) | [
"def",
"create_new_folder",
"(",
"self",
",",
"current_path",
",",
"title",
",",
"subtitle",
",",
"is_package",
")",
":",
"if",
"current_path",
"is",
"None",
":",
"current_path",
"=",
"''",
"if",
"osp",
".",
"isfile",
"(",
"current_path",
")",
":",
"curren... | 51.3125 | 18.75 |
def uci(self, move: Move, *, chess960: Optional[bool] = None) -> str:
"""
Gets the UCI notation of the move.
*chess960* defaults to the mode of the board. Pass ``True`` to force
Chess960 mode.
"""
if chess960 is None:
chess960 = self.chess960
move = self._to_chess960(move)
move = self._from_chess960(chess960, move.from_square, move.to_square, move.promotion, move.drop)
return move.uci() | [
"def",
"uci",
"(",
"self",
",",
"move",
":",
"Move",
",",
"*",
",",
"chess960",
":",
"Optional",
"[",
"bool",
"]",
"=",
"None",
")",
"->",
"str",
":",
"if",
"chess960",
"is",
"None",
":",
"chess960",
"=",
"self",
".",
"chess960",
"move",
"=",
"se... | 35.615385 | 20.230769 |
def _get_timethresh_heuristics(self):
"""
resonably decent hueristics for how much time to wait before
updating progress.
"""
if self.length > 1E5:
time_thresh = 2.5
elif self.length > 1E4:
time_thresh = 2.0
elif self.length > 1E3:
time_thresh = 1.0
else:
time_thresh = 0.5
return time_thresh | [
"def",
"_get_timethresh_heuristics",
"(",
"self",
")",
":",
"if",
"self",
".",
"length",
">",
"1E5",
":",
"time_thresh",
"=",
"2.5",
"elif",
"self",
".",
"length",
">",
"1E4",
":",
"time_thresh",
"=",
"2.0",
"elif",
"self",
".",
"length",
">",
"1E3",
"... | 28.5 | 11.357143 |
def precompute(self, cache_dir=None, swath_usage=0, **kwargs):
"""Generate row and column arrays and store it for later use."""
if kwargs.get('mask') is not None:
LOG.warning("'mask' parameter has no affect during EWA "
"resampling")
del kwargs
source_geo_def = self.source_geo_def
target_geo_def = self.target_geo_def
if cache_dir:
LOG.warning("'cache_dir' is not used by EWA resampling")
# Satpy/PyResample don't support dynamic grids out of the box yet
lons, lats = source_geo_def.get_lonlats()
if isinstance(lons, xr.DataArray):
# get dask arrays
lons = lons.data
lats = lats.data
# we are remapping to a static unchanging grid/area with all of
# its parameters specified
chunks = (2,) + lons.chunks
res = da.map_blocks(self._call_ll2cr, lons, lats,
target_geo_def, swath_usage,
dtype=lons.dtype, chunks=chunks, new_axis=[0])
cols = res[0]
rows = res[1]
# save the dask arrays in the class instance cache
# the on-disk cache will store the numpy arrays
self.cache = {
"rows": rows,
"cols": cols,
}
return None | [
"def",
"precompute",
"(",
"self",
",",
"cache_dir",
"=",
"None",
",",
"swath_usage",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'mask'",
")",
"is",
"not",
"None",
":",
"LOG",
".",
"warning",
"(",
"\"'mask' paramete... | 36.305556 | 19.194444 |
def key_exists_in_list_or_dict(key, lst_or_dct):
"""True if `lst_or_dct[key]` does not raise an Exception"""
if isinstance(lst_or_dct, dict) and key in lst_or_dct:
return True
elif isinstance(lst_or_dct, list):
min_i, max_i = 0, len(lst_or_dct)
if min_i <= key < max_i:
return True
return False | [
"def",
"key_exists_in_list_or_dict",
"(",
"key",
",",
"lst_or_dct",
")",
":",
"if",
"isinstance",
"(",
"lst_or_dct",
",",
"dict",
")",
"and",
"key",
"in",
"lst_or_dct",
":",
"return",
"True",
"elif",
"isinstance",
"(",
"lst_or_dct",
",",
"list",
")",
":",
... | 37.555556 | 11 |
def sum_layout_dimensions(dimensions):
"""
Sum a list of :class:`.LayoutDimension` instances.
"""
min = sum([d.min for d in dimensions if d.min is not None])
max = sum([d.max for d in dimensions if d.max is not None])
preferred = sum([d.preferred for d in dimensions])
return LayoutDimension(min=min, max=max, preferred=preferred) | [
"def",
"sum_layout_dimensions",
"(",
"dimensions",
")",
":",
"min",
"=",
"sum",
"(",
"[",
"d",
".",
"min",
"for",
"d",
"in",
"dimensions",
"if",
"d",
".",
"min",
"is",
"not",
"None",
"]",
")",
"max",
"=",
"sum",
"(",
"[",
"d",
".",
"max",
"for",
... | 39 | 15.666667 |
def read(fname, encoding='utf8', strip_comments=False, **kw):
"""
Load a list of trees from a Newick formatted file.
:param fname: file path.
:param strip_comments: Flag signaling whether to strip comments enclosed in square \
brackets.
:param kw: Keyword arguments are passed through to `Node.create`.
:return: List of Node objects.
"""
kw['strip_comments'] = strip_comments
with io.open(fname, encoding=encoding) as fp:
return load(fp, **kw) | [
"def",
"read",
"(",
"fname",
",",
"encoding",
"=",
"'utf8'",
",",
"strip_comments",
"=",
"False",
",",
"*",
"*",
"kw",
")",
":",
"kw",
"[",
"'strip_comments'",
"]",
"=",
"strip_comments",
"with",
"io",
".",
"open",
"(",
"fname",
",",
"encoding",
"=",
... | 36.923077 | 16.769231 |
def get_conversation_between(self, um_from_user, um_to_user):
""" Returns a conversation between two users """
messages = self.filter(Q(sender=um_from_user, recipients=um_to_user,
sender_deleted_at__isnull=True) |
Q(sender=um_to_user, recipients=um_from_user,
messagerecipient__deleted_at__isnull=True))
return messages | [
"def",
"get_conversation_between",
"(",
"self",
",",
"um_from_user",
",",
"um_to_user",
")",
":",
"messages",
"=",
"self",
".",
"filter",
"(",
"Q",
"(",
"sender",
"=",
"um_from_user",
",",
"recipients",
"=",
"um_to_user",
",",
"sender_deleted_at__isnull",
"=",
... | 62 | 24.571429 |
def alphabetical_formula(self):
"""
Returns a reduced formula string with appended charge
"""
alph_formula = super().alphabetical_formula
chg_str = ""
if self.charge > 0:
chg_str = " +" + formula_double_format(self.charge, False)
elif self.charge < 0:
chg_str = " " + formula_double_format(self.charge, False)
return alph_formula + chg_str | [
"def",
"alphabetical_formula",
"(",
"self",
")",
":",
"alph_formula",
"=",
"super",
"(",
")",
".",
"alphabetical_formula",
"chg_str",
"=",
"\"\"",
"if",
"self",
".",
"charge",
">",
"0",
":",
"chg_str",
"=",
"\" +\"",
"+",
"formula_double_format",
"(",
"self"... | 37.909091 | 13.363636 |
def _inhibitColumnsWithLateral(self, overlaps, lateralConnections):
"""
Performs an experimentatl local inhibition. Local inhibition is
iteratively performed on a column by column basis.
"""
n,m = self.shape
y = np.zeros(n)
s = self.sparsity
L = lateralConnections
desiredWeight = self.codeWeight
inhSignal = np.zeros(n)
sortedIndices = np.argsort(overlaps, kind='mergesort')[::-1]
currentWeight = 0
for i in sortedIndices:
if overlaps[i] < self._stimulusThreshold:
break
inhTooStrong = ( inhSignal[i] >= s )
if not inhTooStrong:
y[i] = 1.
currentWeight += 1
inhSignal[:] += L[i,:]
if self.enforceDesiredWeight and currentWeight == desiredWeight:
break
activeColumns = np.where(y==1.0)[0]
return activeColumns | [
"def",
"_inhibitColumnsWithLateral",
"(",
"self",
",",
"overlaps",
",",
"lateralConnections",
")",
":",
"n",
",",
"m",
"=",
"self",
".",
"shape",
"y",
"=",
"np",
".",
"zeros",
"(",
"n",
")",
"s",
"=",
"self",
".",
"sparsity",
"L",
"=",
"lateralConnecti... | 26.25 | 19.9375 |
def siblings(self, **kwargs):
# type: (Any) -> Any
"""Retrieve the siblings of this `Part` as `Partset`.
Siblings are other Parts sharing the same parent of this `Part`, including the part itself.
:param kwargs: Additional search arguments to search for, check :class:`pykechain.Client.parts`
for additional info
:type kwargs: dict
:return: a set of `Parts` as a :class:`PartSet`. Will be empty if no siblings.
:raises APIError: When an error occurs.
"""
if self.parent_id:
return self._client.parts(parent=self.parent_id, category=self.category, **kwargs)
else:
from pykechain.models.partset import PartSet
return PartSet(parts=[]) | [
"def",
"siblings",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (Any) -> Any",
"if",
"self",
".",
"parent_id",
":",
"return",
"self",
".",
"_client",
".",
"parts",
"(",
"parent",
"=",
"self",
".",
"parent_id",
",",
"category",
"=",
"self",
... | 44.529412 | 24.058824 |
def reduce_lists(d):
"""Replace single item lists in a dictionary with the single item."""
for field in d:
old_data = d[field]
if len(old_data) == 1:
d[field] = old_data[0] | [
"def",
"reduce_lists",
"(",
"d",
")",
":",
"for",
"field",
"in",
"d",
":",
"old_data",
"=",
"d",
"[",
"field",
"]",
"if",
"len",
"(",
"old_data",
")",
"==",
"1",
":",
"d",
"[",
"field",
"]",
"=",
"old_data",
"[",
"0",
"]"
] | 33.833333 | 11.666667 |
def _cursor_position(self, data):
"""
Moves the cursor position.
"""
column, line = self._get_line_and_col(data)
self._move_cursor_to_line(line)
self._move_cursor_to_column(column)
self._last_cursor_pos = self._cursor.position() | [
"def",
"_cursor_position",
"(",
"self",
",",
"data",
")",
":",
"column",
",",
"line",
"=",
"self",
".",
"_get_line_and_col",
"(",
"data",
")",
"self",
".",
"_move_cursor_to_line",
"(",
"line",
")",
"self",
".",
"_move_cursor_to_column",
"(",
"column",
")",
... | 34.625 | 5.375 |
def _replace_numeric_markers(operation, string_parameters):
"""
Replaces qname, format, and numeric markers in the given operation, from
the string_parameters list.
Raises ProgrammingError on wrong number of parameters or bindings
when using qmark. There is no error checking on numeric parameters.
"""
def replace_markers(marker, op, parameters):
param_count = len(parameters)
marker_index = 0
start_offset = 0
while True:
found_offset = op.find(marker, start_offset)
if not found_offset > -1:
break
if marker_index < param_count:
op = op[:found_offset]+op[found_offset:].replace(marker, parameters[marker_index], 1)
start_offset = found_offset + len(parameters[marker_index])
marker_index += 1
else:
raise ProgrammingError("Incorrect number of bindings "
"supplied. The current statement uses "
"%d or more, and there are %d "
"supplied." % (marker_index + 1,
param_count))
if marker_index != 0 and marker_index != param_count:
raise ProgrammingError("Incorrect number of bindings "
"supplied. The current statement uses "
"%d or more, and there are %d supplied." %
(marker_index + 1, param_count))
return op
# replace qmark parameters and format parameters
operation = replace_markers('?', operation, string_parameters)
operation = replace_markers(r'%s', operation, string_parameters)
# replace numbered parameters
# Go through them backwards so smaller numbers don't replace
# parts of larger ones
for index in range(len(string_parameters), 0, -1):
operation = operation.replace(':' + str(index),
string_parameters[index - 1])
return operation | [
"def",
"_replace_numeric_markers",
"(",
"operation",
",",
"string_parameters",
")",
":",
"def",
"replace_markers",
"(",
"marker",
",",
"op",
",",
"parameters",
")",
":",
"param_count",
"=",
"len",
"(",
"parameters",
")",
"marker_index",
"=",
"0",
"start_offset",... | 47.204545 | 22.386364 |
def _request(self, method, uri_relative, request_bytes, params,
custom_headers):
"""
:type method: str
:type uri_relative: str
:type request_bytes: bytes
:type params: dict[str, str]
:type custom_headers: dict[str, str]
:return: BunqResponseRaw
"""
uri_relative_with_params = self._append_params_to_uri(uri_relative,
params)
if uri_relative not in self._URIS_NOT_REQUIRING_ACTIVE_SESSION:
if self._api_context.ensure_session_active():
from bunq.sdk.context import BunqContext
BunqContext.update_api_context(self._api_context)
all_headers = self._get_all_headers(
method,
uri_relative_with_params,
request_bytes,
custom_headers
)
response = requests.request(
method,
self._get_uri_full(uri_relative_with_params),
data=request_bytes,
headers=all_headers,
proxies={self._FIELD_PROXY_HTTPS: self._api_context.proxy_url},
)
self._assert_response_success(response)
if self._api_context.installation_context is not None:
security.validate_response(
self._api_context.installation_context.public_key_server,
response.status_code,
response.content,
response.headers
)
return self._create_bunq_response_raw(response) | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"uri_relative",
",",
"request_bytes",
",",
"params",
",",
"custom_headers",
")",
":",
"uri_relative_with_params",
"=",
"self",
".",
"_append_params_to_uri",
"(",
"uri_relative",
",",
"params",
")",
"if",
"uri_r... | 33.130435 | 19.217391 |
def vector_to_rgb(image):
"""
Convert an Vector ANTsImage to a RGB ANTsImage
Arguments
---------
image : ANTsImage
RGB image to be converted
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'), pixeltype='unsigned char')
>>> img_rgb = img.clone().scalar_to_rgb()
>>> img_vec = img_rgb.rgb_to_vector()
>>> img_rgb2 = img_vec.vector_to_rgb()
"""
if image.pixeltype != 'unsigned char':
image = image.clone('unsigned char')
idim = image.dimension
libfn = utils.get_lib_fn('VectorToRgb%i' % idim)
new_ptr = libfn(image.pointer)
new_img = iio.ANTsImage(pixeltype=image.pixeltype, dimension=image.dimension,
components=3, pointer=new_ptr, is_rgb=True)
return new_img | [
"def",
"vector_to_rgb",
"(",
"image",
")",
":",
"if",
"image",
".",
"pixeltype",
"!=",
"'unsigned char'",
":",
"image",
"=",
"image",
".",
"clone",
"(",
"'unsigned char'",
")",
"idim",
"=",
"image",
".",
"dimension",
"libfn",
"=",
"utils",
".",
"get_lib_fn... | 28.275862 | 19.586207 |
def mat2euler(rmat, axes="sxyz"):
"""
Converts given rotation matrix to euler angles in radian.
Args:
rmat: 3x3 rotation matrix
axes: One of 24 axis sequences as string or encoded tuple
Returns:
converted euler angles in radian vec3 float
"""
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i + parity]
k = _NEXT_AXIS[i - parity + 1]
M = np.array(rmat, dtype=np.float32, copy=False)[:3, :3]
if repetition:
sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k])
if sy > EPS:
ax = math.atan2(M[i, j], M[i, k])
ay = math.atan2(sy, M[i, i])
az = math.atan2(M[j, i], -M[k, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(sy, M[i, i])
az = 0.0
else:
cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i])
if cy > EPS:
ax = math.atan2(M[k, j], M[k, k])
ay = math.atan2(-M[k, i], cy)
az = math.atan2(M[j, i], M[i, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(-M[k, i], cy)
az = 0.0
if parity:
ax, ay, az = -ax, -ay, -az
if frame:
ax, az = az, ax
return vec((ax, ay, az)) | [
"def",
"mat2euler",
"(",
"rmat",
",",
"axes",
"=",
"\"sxyz\"",
")",
":",
"try",
":",
"firstaxis",
",",
"parity",
",",
"repetition",
",",
"frame",
"=",
"_AXES2TUPLE",
"[",
"axes",
".",
"lower",
"(",
")",
"]",
"except",
"(",
"AttributeError",
",",
"KeyEr... | 29.574468 | 17.404255 |
def _decrypt_asymmetric(
self,
decryption_algorithm,
decryption_key,
cipher_text,
padding_method,
hashing_algorithm=None):
"""
Encrypt data using asymmetric decryption.
Args:
decryption_algorithm (CryptographicAlgorithm): An enumeration
specifying the asymmetric decryption algorithm to use for
decryption. Required.
decryption_key (bytes): The bytes of the private key to use for
decryption. Required.
cipher_text (bytes): The bytes to be decrypted. Required.
padding_method (PaddingMethod): An enumeration specifying the
padding method to use with the asymmetric decryption
algorithm. Required.
hashing_algorithm (HashingAlgorithm): An enumeration specifying
the hashing algorithm to use with the decryption padding
method. Required, if the padding method is OAEP. Optional
otherwise, defaults to None.
Returns:
dict: A dictionary containing the decrypted data, with at least
the following key/value field:
* plain_text - the bytes of the decrypted data
Raises:
InvalidField: Raised when the algorithm is unsupported or the
length is incompatible with the algorithm.
CryptographicFailure: Raised when the key generation process
fails.
"""
if decryption_algorithm == enums.CryptographicAlgorithm.RSA:
if padding_method == enums.PaddingMethod.OAEP:
hash_algorithm = self._encryption_hash_algorithms.get(
hashing_algorithm
)
if hash_algorithm is None:
raise exceptions.InvalidField(
"The hashing algorithm '{0}' is not supported for "
"asymmetric decryption.".format(hashing_algorithm)
)
padding_method = asymmetric_padding.OAEP(
mgf=asymmetric_padding.MGF1(
algorithm=hash_algorithm()
),
algorithm=hash_algorithm(),
label=None
)
elif padding_method == enums.PaddingMethod.PKCS1v15:
padding_method = asymmetric_padding.PKCS1v15()
else:
raise exceptions.InvalidField(
"The padding method '{0}' is not supported for asymmetric "
"decryption.".format(padding_method)
)
backend = default_backend()
try:
private_key = backend.load_der_private_key(
decryption_key,
None
)
except Exception:
try:
private_key = backend.load_pem_private_key(
decryption_key,
None
)
except Exception:
raise exceptions.CryptographicFailure(
"The private key bytes could not be loaded."
)
plain_text = private_key.decrypt(
cipher_text,
padding_method
)
return plain_text
else:
raise exceptions.InvalidField(
"The cryptographic algorithm '{0}' is not supported for "
"asymmetric decryption.".format(decryption_algorithm)
) | [
"def",
"_decrypt_asymmetric",
"(",
"self",
",",
"decryption_algorithm",
",",
"decryption_key",
",",
"cipher_text",
",",
"padding_method",
",",
"hashing_algorithm",
"=",
"None",
")",
":",
"if",
"decryption_algorithm",
"==",
"enums",
".",
"CryptographicAlgorithm",
".",
... | 40.05618 | 19.808989 |
def custom(self, code, message):
"""
Specific server side errors use: -32000 to -32099
reserved for implementation-defined server-errors
"""
if -32000 < code or -32099 > code:
code = -32603
message = 'Internal error'
return JResponse(jsonrpc={
'id': self.rid,
'error': {'code': code, 'message': message},
}) | [
"def",
"custom",
"(",
"self",
",",
"code",
",",
"message",
")",
":",
"if",
"-",
"32000",
"<",
"code",
"or",
"-",
"32099",
">",
"code",
":",
"code",
"=",
"-",
"32603",
"message",
"=",
"'Internal error'",
"return",
"JResponse",
"(",
"jsonrpc",
"=",
"{"... | 33.333333 | 10.5 |
def main():
"""
Do the things!
Return: 0
Exceptions:
"""
description = 'Letter - a commandline interface'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('--gmail', action='store_true', help='Send via Gmail', )
args = parser.parse_args()
to = raw_input('To address > ')
subject = raw_input('Subject > ')
body = raw_input('Your Message > ')
if args.gmail:
user = fromaddr = raw_input('Gmail Address > ')
pw = getpass.getpass()
postie = letter.GmailPostman(user=user, pw=pw)
else:
postie = letter.Postman() # Unauthorized SMTP, localhost:25
fromaddr = raw_input('From address > ')
class Message(letter.Letter):
Postie = postie
From = fromaddr
To = to
Subject = subject
Body = body
return 0 | [
"def",
"main",
"(",
")",
":",
"description",
"=",
"'Letter - a commandline interface'",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
")",
"parser",
".",
"add_argument",
"(",
"'--gmail'",
",",
"action",
"=",
"'store_true... | 25 | 21.114286 |
def level(self, img, level):
"""Get image level.
Parameters
----------
img : `PIL.Image`
Input image.
level : `int`
Level number.
Returns
-------
`PIL.Image`
Converted image.
"""
if level < self.levels - 1:
width, height = img.size
scale = reduce(lambda x, y: x * y,
islice(self.level_scale, level, self.levels))
img = img.resize((width // scale, height // scale), self.scale)
return img | [
"def",
"level",
"(",
"self",
",",
"img",
",",
"level",
")",
":",
"if",
"level",
"<",
"self",
".",
"levels",
"-",
"1",
":",
"width",
",",
"height",
"=",
"img",
".",
"size",
"scale",
"=",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"*",
"... | 26.47619 | 18.47619 |
def load(filename, relative_to_module=None, compound=None, coords_only=False,
rigid=False, use_parmed=False, smiles=False, **kwargs):
"""Load a file into an mbuild compound.
Files are read using the MDTraj package unless the `use_parmed` argument is
specified as True. Please refer to http://mdtraj.org/1.8.0/load_functions.html
for formats supported by MDTraj and https://parmed.github.io/ParmEd/html/
readwrite.html for formats supported by ParmEd.
Parameters
----------
filename : str
Name of the file from which to load atom and bond information.
relative_to_module : str, optional, default=None
Instead of looking in the current working directory, look for the file
where this module is defined. This is typically used in Compound
classes that will be instantiated from a different directory
(such as the Compounds located in mbuild.lib).
compound : mb.Compound, optional, default=None
Existing compound to load atom and bond information into.
coords_only : bool, optional, default=False
Only load the coordinates into an existing compoint.
rigid : bool, optional, default=False
Treat the compound as a rigid body
use_parmed : bool, optional, default=False
Use readers from ParmEd instead of MDTraj.
smiles: bool, optional, default=False
Use Open Babel to parse filename as a SMILES string
or file containing a SMILES string
**kwargs : keyword arguments
Key word arguments passed to mdTraj for loading.
Returns
-------
compound : mb.Compound
"""
# Handle mbuild *.py files containing a class that wraps a structure file
# in its own folder. E.g., you build a system from ~/foo.py and it imports
# from ~/bar/baz.py where baz.py loads ~/bar/baz.pdb.
if relative_to_module:
script_path = os.path.realpath(
sys.modules[relative_to_module].__file__)
file_dir = os.path.dirname(script_path)
filename = os.path.join(file_dir, filename)
if compound is None:
compound = Compound()
# Handle the case of a xyz file, which must use an internal reader
extension = os.path.splitext(filename)[-1]
if extension == '.xyz' and not 'top' in kwargs:
if coords_only:
tmp = read_xyz(filename)
if tmp.n_particles != compound.n_particles:
raise ValueError('Number of atoms in {filename} does not match'
' {compound}'.format(**locals()))
ref_and_compound = zip(tmp._particles(include_ports=False),
compound.particles(include_ports=False))
for ref_particle, particle in ref_and_compound:
particle.pos = ref_particle.pos
else:
compound = read_xyz(filename)
return compound
if use_parmed:
warn(
"use_parmed set to True. Bonds may be inferred from inter-particle "
"distances and standard residue templates!")
structure = pmd.load_file(filename, structure=True, **kwargs)
compound.from_parmed(structure, coords_only=coords_only)
elif smiles:
pybel = import_('pybel')
# First we try treating filename as a SMILES string
try:
mymol = pybel.readstring("smi", filename)
# Now we treat it as a filename
except(OSError, IOError):
# For now, we only support reading in a single smiles molecule,
# but pybel returns a generator, so we get the first molecule
# and warn the user if there is more
mymol_generator = pybel.readfile("smi", filename)
mymol_list = list(mymol_generator)
if len(mymol_list) == 1:
mymol = mymol_list[0]
else:
mymol = mymol_list[0]
warn("More than one SMILES string in file, more than one SMILES "
"string is not supported, using {}".format(mymol.write("smi")))
tmp_dir = tempfile.mkdtemp()
temp_file = os.path.join(tmp_dir, 'smiles_to_mol2_intermediate.mol2')
mymol.make3D()
mymol.write("MOL2", temp_file)
structure = pmd.load_file(temp_file, structure=True, **kwargs)
compound.from_parmed(structure, coords_only=coords_only)
else:
traj = md.load(filename, **kwargs)
compound.from_trajectory(traj, frame=-1, coords_only=coords_only)
if rigid:
compound.label_rigid_bodies()
return compound | [
"def",
"load",
"(",
"filename",
",",
"relative_to_module",
"=",
"None",
",",
"compound",
"=",
"None",
",",
"coords_only",
"=",
"False",
",",
"rigid",
"=",
"False",
",",
"use_parmed",
"=",
"False",
",",
"smiles",
"=",
"False",
",",
"*",
"*",
"kwargs",
"... | 42.216981 | 21.311321 |
def set_flair_csv(self, subreddit, flair_mapping):
"""Set flair for a group of users in the given subreddit.
flair_mapping should be a list of dictionaries with the following keys:
`user`: the user name,
`flair_text`: the flair text for the user (optional),
`flair_css_class`: the flair css class for the user (optional)
:returns: The json response from the server.
"""
if not flair_mapping:
raise errors.ClientException('flair_mapping must be set')
item_order = ['user', 'flair_text', 'flair_css_class']
lines = []
for mapping in flair_mapping:
if 'user' not in mapping:
raise errors.ClientException('flair_mapping must '
'contain `user` key')
lines.append(','.join([mapping.get(x, '') for x in item_order]))
response = []
while len(lines):
data = {'r': six.text_type(subreddit),
'flair_csv': '\n'.join(lines[:100])}
response.extend(self.request_json(self.config['flaircsv'],
data=data))
lines = lines[100:]
evict = self.config['flairlist'].format(
subreddit=six.text_type(subreddit))
self.evict(evict)
return response | [
"def",
"set_flair_csv",
"(",
"self",
",",
"subreddit",
",",
"flair_mapping",
")",
":",
"if",
"not",
"flair_mapping",
":",
"raise",
"errors",
".",
"ClientException",
"(",
"'flair_mapping must be set'",
")",
"item_order",
"=",
"[",
"'user'",
",",
"'flair_text'",
"... | 43.129032 | 18.870968 |
def __create_map(self, map_size):
'''
Create map.
References:
- https://qiita.com/kusano_t/items/487eec15d42aace7d685
'''
import random
import numpy as np
from itertools import product
news = ['n', 'e', 'w', 's']
m, n = map_size
SPACE = self.SPACE
WALL = self.WALL
START = self.START
GOAL = self.GOAL
memo = np.array([i for i in range(n * m)])
memo = memo.reshape(m, n)
# 迷路を初期化
maze = [[SPACE for _ in range(2 * n + 1)] for _ in range(2 * m + 1)]
maze[self.START_POS[0]][self.START_POS[1]] = START
self.__goal_pos = (2 * m - 1, 2 * n - 1)
maze[2 * m - 1][2 * n - 1] = GOAL
for i, j in product(range(2 * m + 1), range(2 * n + 1)):
if i % 2 == 0 or j % 2 == 0:
maze[i][j] = WALL
while (memo != 0).any():
x1 = random.choice(range(m))
y1 = random.choice(range(n))
direction = random.choice(news)
if direction == 'e':
x2, y2 = x1, y1 + 1
elif direction == 'w':
x2, y2 = x1, y1 - 1
elif direction == 'n':
x2, y2 = x1 - 1, y1
elif direction == 's':
x2, y2 = x1 + 1, y1
# 範囲外の場合はcontinue
if (x2 < 0) or (x2 >= m) or (y2 < 0) or (y2 >= n):
continue
if memo[x1, y1] != memo[x2, y2]:
tmp_min = min(memo[x1, y1], memo[x2, y2])
tmp_max = max(memo[x1, y1], memo[x2, y2])
# メモの更新
memo[memo == tmp_max] = tmp_min
# 壁を壊す
maze[x1 + x2 + 1][y1 + y2 + 1] = SPACE
maze_arr = np.array(maze)
return maze_arr | [
"def",
"__create_map",
"(",
"self",
",",
"map_size",
")",
":",
"import",
"random",
"import",
"numpy",
"as",
"np",
"from",
"itertools",
"import",
"product",
"news",
"=",
"[",
"'n'",
",",
"'e'",
",",
"'w'",
",",
"'s'",
"]",
"m",
",",
"n",
"=",
"map_siz... | 27.828125 | 18.671875 |
def add_optional_parameters(detail_json, detail, rating, rating_n, popularity, current_popularity, time_spent):
"""
check for optional return parameters and add them to the result json
:param detail_json:
:param detail:
:param rating:
:param rating_n:
:param popularity:
:param current_popularity:
:param time_spent:
:return:
"""
if rating is not None:
detail_json["rating"] = rating
elif "rating" in detail:
detail_json["rating"] = detail["rating"]
if rating_n is not None:
detail_json["rating_n"] = rating_n
if "international_phone_number" in detail:
detail_json["international_phone_number"] = detail["international_phone_number"]
if current_popularity is not None:
detail_json["current_popularity"] = current_popularity
if popularity is not None:
popularity, wait_times = get_popularity_for_day(popularity)
detail_json["populartimes"] = popularity
detail_json["time_wait"] = wait_times
if time_spent is not None:
detail_json["time_spent"] = time_spent
return detail_json | [
"def",
"add_optional_parameters",
"(",
"detail_json",
",",
"detail",
",",
"rating",
",",
"rating_n",
",",
"popularity",
",",
"current_popularity",
",",
"time_spent",
")",
":",
"if",
"rating",
"is",
"not",
"None",
":",
"detail_json",
"[",
"\"rating\"",
"]",
"="... | 29.567568 | 21.351351 |
def autocomplete_view(self, request):
"""
Searches in the fields of the given related model and returns the
result as a simple string to be used by the jQuery Autocomplete plugin
"""
query = request.GET.get('q', None)
app_label = request.GET.get('app_label', None)
model_name = request.GET.get('model_name', None)
search_fields = request.GET.get('search_fields', None)
object_pk = request.GET.get('object_pk', None)
try:
to_string_function = self.related_string_functions[model_name]
except KeyError:
to_string_function = lambda x: str(x)
if search_fields and app_label and model_name and (query or object_pk):
def construct_search(field_name):
# use different lookup methods depending on the notation
if field_name.startswith('^'):
fmt, name = "{}__istartswith", field_name[1:]
elif field_name.startswith('='):
fmt, name = "{}__iexact", field_name[1:]
elif field_name.startswith('@'):
fmt, name = "{}__search", field_name[1:]
else:
fmt, name = "{}__icontains", field_name
return fmt.format(name)
model = apps.get_model(app_label, model_name)
queryset = model._default_manager.all()
data = ''
if query:
for bit in query.split():
or_queries = [
models.Q(**{construct_search(smart_str(field_name)): smart_str(bit)})
for field_name
in search_fields.split(',')
]
other_qs = QuerySet(model)
other_qs.query.select_related = queryset.query.select_related
other_qs = other_qs.filter(reduce(operator.or_, or_queries))
queryset = queryset & other_qs
if self.autocomplete_limit:
queryset = queryset[:self.autocomplete_limit]
data = ''.join([
'{}|{}\n'.format(to_string_function(f), f.pk)
for f
in queryset
])
elif object_pk:
try:
obj = queryset.get(pk=object_pk)
except:
pass
else:
data = to_string_function(obj)
return HttpResponse(data)
return HttpResponseNotFound() | [
"def",
"autocomplete_view",
"(",
"self",
",",
"request",
")",
":",
"query",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'q'",
",",
"None",
")",
"app_label",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'app_label'",
",",
"None",
")",
"model_name",
... | 40.870968 | 18.483871 |
def can_access_objective_hierarchy(self):
"""Tests if this user can perform hierarchy queries.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a PermissionDenied. This is intended as a
hint to an an application that may not offer traversal functions
to unauthorized users.
return: (boolean) - false if hierarchy traversal methods are not
authorized, true otherwise
compliance: mandatory - This method must be implemented.
"""
url_path = construct_url('authorization',
bank_id=self._catalog_idstr)
return self._get_request(url_path)['objectiveHierarchyHints']['canAccessHierarchy'] | [
"def",
"can_access_objective_hierarchy",
"(",
"self",
")",
":",
"url_path",
"=",
"construct_url",
"(",
"'authorization'",
",",
"bank_id",
"=",
"self",
".",
"_catalog_idstr",
")",
"return",
"self",
".",
"_get_request",
"(",
"url_path",
")",
"[",
"'objectiveHierarch... | 47.411765 | 23.235294 |
def analyze_one_classification_result(storage_client, file_path,
adv_batch, dataset_batches,
dataset_meta):
"""Reads and analyzes one classification result.
This method reads file with classification result and counts
how many images were classified correctly and incorrectly,
how many times target class was hit and total number of images.
Args:
storage_client: instance of CompetitionStorageClient
file_path: result file path
adv_batch: AversarialBatches.data[adv_batch_id]
adv_batch_id is stored in each ClassificationBatch entity
dataset_batches: instance of DatasetBatches
dataset_meta: instance of DatasetMetadata
Returns:
Tuple of (count_correctly_classified, count_errors, count_hit_target_class,
num_images)
"""
class_result = read_classification_results(storage_client, file_path)
if class_result is None:
return 0, 0, 0, 0
adv_images = adv_batch['images']
dataset_batch_images = (
dataset_batches.data[adv_batch['dataset_batch_id']]['images'])
count_correctly_classified = 0
count_errors = 0
count_hit_target_class = 0
num_images = 0
for adv_img_id, label in iteritems(class_result):
if adv_img_id not in adv_images:
continue
num_images += 1
clean_image_id = adv_images[adv_img_id]['clean_image_id']
dataset_image_id = (
dataset_batch_images[clean_image_id]['dataset_image_id'])
if label == dataset_meta.get_true_label(dataset_image_id):
count_correctly_classified += 1
else:
count_errors += 1
if label == dataset_meta.get_target_class(dataset_image_id):
count_hit_target_class += 1
return (count_correctly_classified, count_errors,
count_hit_target_class, num_images) | [
"def",
"analyze_one_classification_result",
"(",
"storage_client",
",",
"file_path",
",",
"adv_batch",
",",
"dataset_batches",
",",
"dataset_meta",
")",
":",
"class_result",
"=",
"read_classification_results",
"(",
"storage_client",
",",
"file_path",
")",
"if",
"class_r... | 38.282609 | 18.869565 |
def _clean_item(self, item):
'''
Cleans the item to be logged
'''
item_copy = dict(item)
del item_copy['body']
del item_copy['links']
del item_copy['response_headers']
del item_copy['request_headers']
del item_copy['status_code']
del item_copy['status_msg']
item_copy['action'] = 'ack'
item_copy['logger'] = self.logger.name
item_copy
return item_copy | [
"def",
"_clean_item",
"(",
"self",
",",
"item",
")",
":",
"item_copy",
"=",
"dict",
"(",
"item",
")",
"del",
"item_copy",
"[",
"'body'",
"]",
"del",
"item_copy",
"[",
"'links'",
"]",
"del",
"item_copy",
"[",
"'response_headers'",
"]",
"del",
"item_copy",
... | 28.0625 | 12.8125 |
def _geom_type(self, source):
"""gets geometry type(s) of specified layer"""
if isinstance(source, AbstractLayer):
query = source.orig_query
else:
query = 'SELECT * FROM "{table}"'.format(table=source)
resp = self.sql_client.send(
utils.minify_sql((
'SELECT',
' CASE WHEN ST_GeometryType(the_geom)',
' in (\'ST_Point\', \'ST_MultiPoint\')',
' THEN \'point\'',
' WHEN ST_GeometryType(the_geom)',
' in (\'ST_LineString\', \'ST_MultiLineString\')',
' THEN \'line\'',
' WHEN ST_GeometryType(the_geom)',
' in (\'ST_Polygon\', \'ST_MultiPolygon\')',
' THEN \'polygon\'',
' ELSE null END AS geom_type,',
' count(*) as cnt',
'FROM ({query}) AS _wrap',
'WHERE the_geom IS NOT NULL',
'GROUP BY 1',
'ORDER BY 2 DESC',
)).format(query=query),
**DEFAULT_SQL_ARGS)
if resp['total_rows'] > 1:
warn('There are multiple geometry types in {query}: '
'{geoms}. Styling by `{common_geom}`, the most common'.format(
query=query,
geoms=','.join(g['geom_type'] for g in resp['rows']),
common_geom=resp['rows'][0]['geom_type']))
elif resp['total_rows'] == 0:
raise ValueError('No geometry for layer. Check all layer tables '
'and queries to ensure there are geometries.')
return resp['rows'][0]['geom_type'] | [
"def",
"_geom_type",
"(",
"self",
",",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"AbstractLayer",
")",
":",
"query",
"=",
"source",
".",
"orig_query",
"else",
":",
"query",
"=",
"'SELECT * FROM \"{table}\"'",
".",
"format",
"(",
"table",
... | 48.527778 | 14.75 |
def kill_child_processes() -> None:
"""
Kills children of this process that were registered in the
:data:`processes` variable.
Use with ``@atexit.register``.
"""
timeout_sec = 5
for p in processes:
try:
p.wait(timeout_sec)
except TimeoutExpired:
# failed to close
p.kill() | [
"def",
"kill_child_processes",
"(",
")",
"->",
"None",
":",
"timeout_sec",
"=",
"5",
"for",
"p",
"in",
"processes",
":",
"try",
":",
"p",
".",
"wait",
"(",
"timeout_sec",
")",
"except",
"TimeoutExpired",
":",
"# failed to close",
"p",
".",
"kill",
"(",
"... | 24.285714 | 14.142857 |
def FilePattern(pattern, settings, **kwargs):
"""Factory method returns LocalFilePattern or GoogleStorageFilePattern
"""
url = _urlparse(pattern)
if url.scheme == 'gs':
return GoogleStorageFilePattern(pattern, settings, **kwargs)
else:
assert url.scheme == 'file'
return LocalFilePattern(pattern, settings, **kwargs) | [
"def",
"FilePattern",
"(",
"pattern",
",",
"settings",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"_urlparse",
"(",
"pattern",
")",
"if",
"url",
".",
"scheme",
"==",
"'gs'",
":",
"return",
"GoogleStorageFilePattern",
"(",
"pattern",
",",
"settings",
... | 39.111111 | 12.777778 |
def _grains():
'''
Helper function to the grains from the proxied devices.
'''
client = _get_client()
# This is a collection of the configuration of all running devices under NSO
ret = client.get_datastore(DatastoreType.RUNNING)
GRAINS_CACHE.update(ret)
return GRAINS_CACHE | [
"def",
"_grains",
"(",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"# This is a collection of the configuration of all running devices under NSO",
"ret",
"=",
"client",
".",
"get_datastore",
"(",
"DatastoreType",
".",
"RUNNING",
")",
"GRAINS_CACHE",
".",
"update",... | 33 | 23 |
def SAR(cpu, dest, src):
"""
Shift arithmetic right.
The shift arithmetic right (SAR) and shift logical right (SHR) instructions shift the bits of the destination operand to
the right (toward less significant bit locations). For each shift count, the least significant bit of the destination
operand is shifted into the CF flag, and the most significant bit is either set or cleared depending on the instruction
type. The SHR instruction clears the most significant bit. the SAR instruction sets or clears the most significant bit
to correspond to the sign (most significant bit) of the original value in the destination operand. In effect, the SAR
instruction fills the empty bit position's shifted value with the sign of the unshifted value
:param cpu: current CPU.
:param dest: destination operand.
:param src: source operand.
"""
OperandSize = dest.size
countMask = {8: 0x1f,
16: 0x1f,
32: 0x1f,
64: 0x3f}[OperandSize]
count = src.read() & countMask
value = dest.read()
res = Operators.SAR(OperandSize, value, Operators.ZEXTEND(count, OperandSize))
dest.write(res)
SIGN_MASK = (1 << (OperandSize - 1))
# We can't use this one as the 'true' expression gets eagerly calculated even on count == 0 + cpu.CF = Operators.ITE(count!=0, ((value >> Operators.ZEXTEND(count-1, OperandSize)) & 1) !=0, cpu.CF)
# cpu.CF = Operators.ITE(count!=0, ((value >> Operators.ZEXTEND(count-1, OperandSize)) & 1) !=0, cpu.CF)
if issymbolic(count):
# We can't use this one as the EXTRACT op needs the offset arguments to be concrete
# cpu.CF = Operators.ITE(count!=0, Operands.EXTRACT(value,count-1,1) !=0, cpu.CF)
cpu.CF = Operators.ITE(Operators.AND(count != 0, count <= OperandSize), ((value >> Operators.ZEXTEND(count - 1, OperandSize)) & 1) != 0, cpu.CF)
else:
if count != 0:
if count > OperandSize:
count = OperandSize
cpu.CF = Operators.EXTRACT(value, count - 1, 1) != 0
# on count == 0 AF is unaffected, for count > 0, AF is undefined.
# in either case, do not touch AF
cpu.ZF = Operators.ITE(count != 0, res == 0, cpu.ZF)
cpu.SF = Operators.ITE(count != 0, (res & SIGN_MASK) != 0, cpu.SF)
cpu.OF = Operators.ITE(count == 1, False, cpu.OF)
cpu.PF = Operators.ITE(count != 0, cpu._calculate_parity_flag(res), cpu.PF) | [
"def",
"SAR",
"(",
"cpu",
",",
"dest",
",",
"src",
")",
":",
"OperandSize",
"=",
"dest",
".",
"size",
"countMask",
"=",
"{",
"8",
":",
"0x1f",
",",
"16",
":",
"0x1f",
",",
"32",
":",
"0x1f",
",",
"64",
":",
"0x3f",
"}",
"[",
"OperandSize",
"]",... | 53.583333 | 34.958333 |
def as_tag(self, tag_func):
"""
Creates a tag expecting the format:
``{% tag_name as var_name %}``
The decorated func returns the value that is given to
``var_name`` in the template.
"""
@wraps(tag_func)
def tag_wrapper(parser, token):
class AsTagNode(template.Node):
def render(self, context):
parts = token.split_contents()
# Resolve variables if their names are given.
def resolve(arg):
try:
return template.Variable(arg).resolve(context)
except template.VariableDoesNotExist:
return arg
args, kwargs = [], {}
for arg in parts[1:-2]:
if "=" in arg:
name, val = arg.split("=", 1)
if name in tag_func.__code__.co_varnames:
kwargs[name] = resolve(val)
continue
args.append(resolve(arg))
context[parts[-1]] = tag_func(*args, **kwargs)
return ""
return AsTagNode()
return self.tag(tag_wrapper) | [
"def",
"as_tag",
"(",
"self",
",",
"tag_func",
")",
":",
"@",
"wraps",
"(",
"tag_func",
")",
"def",
"tag_wrapper",
"(",
"parser",
",",
"token",
")",
":",
"class",
"AsTagNode",
"(",
"template",
".",
"Node",
")",
":",
"def",
"render",
"(",
"self",
",",... | 41.483871 | 11.032258 |
def _fetch(self, endpoint_name, **params):
"""
Wrapper for making an api request from giphy
"""
params['api_key'] = self.api_key
resp = requests.get(self._endpoint(endpoint_name), params=params)
resp.raise_for_status()
data = resp.json()
self._check_or_raise(data.get('meta', {}))
return data | [
"def",
"_fetch",
"(",
"self",
",",
"endpoint_name",
",",
"*",
"*",
"params",
")",
":",
"params",
"[",
"'api_key'",
"]",
"=",
"self",
".",
"api_key",
"resp",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"_endpoint",
"(",
"endpoint_name",
")",
",",
"... | 27.307692 | 17 |
def write_zarr(
self,
store: Union[MutableMapping, PathLike],
chunks: Union[bool, int, Tuple[int, ...]],
):
"""Write a hierarchical Zarr array store.
Parameters
----------
store
The filename, a :class:`~typing.MutableMapping`, or a Zarr storage class.
chunks
Chunk shape.
"""
from .readwrite.write import write_zarr
write_zarr(store, self, chunks=chunks) | [
"def",
"write_zarr",
"(",
"self",
",",
"store",
":",
"Union",
"[",
"MutableMapping",
",",
"PathLike",
"]",
",",
"chunks",
":",
"Union",
"[",
"bool",
",",
"int",
",",
"Tuple",
"[",
"int",
",",
"...",
"]",
"]",
",",
")",
":",
"from",
".",
"readwrite"... | 28.5 | 19.625 |
def execute(self, eopatch):
""" Execute function which adds new vector layer to the EOPatch
:param eopatch: input EOPatch
:type eopatch: EOPatch
:return: New EOPatch with added vector layer
:rtype: EOPatch
"""
for raster_ft, raster_fn, vector_fn in self.feature_gen(eopatch):
vector_ft = FeatureType.VECTOR_TIMELESS if raster_ft.is_timeless() else FeatureType.VECTOR
raster = eopatch[raster_ft][raster_fn]
height, width = raster.shape[:2] if raster_ft.is_timeless() else raster.shape[1: 3]
if self.raster_dtype:
raster = raster.astype(self.raster_dtype)
data_transform = rasterio.transform.from_bounds(*eopatch.bbox, width=width, height=height)
crs = eopatch.bbox.get_crs()
if raster_ft.is_timeless():
eopatch[vector_ft][vector_fn] = self._vectorize_single_raster(raster, data_transform, crs)
else:
gpd_list = [self._vectorize_single_raster(raster[time_idx, ...], data_transform, crs,
timestamp=eopatch.timestamp[time_idx])
for time_idx in range(raster.shape[0])]
eopatch[vector_ft][vector_fn] = GeoDataFrame(pd.concat(gpd_list, ignore_index=True),
crs=gpd_list[0].crs)
return eopatch | [
"def",
"execute",
"(",
"self",
",",
"eopatch",
")",
":",
"for",
"raster_ft",
",",
"raster_fn",
",",
"vector_fn",
"in",
"self",
".",
"feature_gen",
"(",
"eopatch",
")",
":",
"vector_ft",
"=",
"FeatureType",
".",
"VECTOR_TIMELESS",
"if",
"raster_ft",
".",
"i... | 44.75 | 30.4375 |
def from_query_string(cls, schema, qs=None):
"""
Extract a page from the current query string.
:param qs: a query string dictionary (`request.args` will be used if omitted)
"""
dct = load_query_string_data(schema, qs)
return cls.from_dict(dct) | [
"def",
"from_query_string",
"(",
"cls",
",",
"schema",
",",
"qs",
"=",
"None",
")",
":",
"dct",
"=",
"load_query_string_data",
"(",
"schema",
",",
"qs",
")",
"return",
"cls",
".",
"from_dict",
"(",
"dct",
")"
] | 31.666667 | 17.444444 |
def area_of_polygon(polygon):
"""
Returns the area of an OpenQuake polygon in square kilometres
"""
lon0 = np.mean(polygon.lons)
lat0 = np.mean(polygon.lats)
# Transform to lamber equal area projection
x, y = lonlat_to_laea(polygon.lons, polygon.lats, lon0, lat0)
# Build shapely polygons
poly = geometry.Polygon(zip(x, y))
return poly.area | [
"def",
"area_of_polygon",
"(",
"polygon",
")",
":",
"lon0",
"=",
"np",
".",
"mean",
"(",
"polygon",
".",
"lons",
")",
"lat0",
"=",
"np",
".",
"mean",
"(",
"polygon",
".",
"lats",
")",
"# Transform to lamber equal area projection",
"x",
",",
"y",
"=",
"lo... | 33.636364 | 10.727273 |
def NDLimitExceeded_originator_switch_info_switchVcsId(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
NDLimitExceeded = ET.SubElement(config, "NDLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
originator_switch_info = ET.SubElement(NDLimitExceeded, "originator-switch-info")
switchVcsId = ET.SubElement(originator_switch_info, "switchVcsId")
switchVcsId.text = kwargs.pop('switchVcsId')
callback = kwargs.pop('callback', self._callback)
return callback(config) | [
"def",
"NDLimitExceeded_originator_switch_info_switchVcsId",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"NDLimitExceeded",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"NDLimitExceeded\"",
... | 52.454545 | 25.454545 |
def format_pattrs(pattrs: List['api.PrettyAttribute']) -> str:
"""Generates repr string given a list of pattrs."""
output = []
pattrs.sort(
key=lambda x: (
_FORMATTER[x.display_group].display_index,
x.display_group,
x.name,
)
)
for display_group, grouped_pattrs in groupby(pattrs, lambda x: x.display_group):
output.append(
_FORMATTER[display_group].formatter(display_group, grouped_pattrs)
)
return '\n'.join(output) | [
"def",
"format_pattrs",
"(",
"pattrs",
":",
"List",
"[",
"'api.PrettyAttribute'",
"]",
")",
"->",
"str",
":",
"output",
"=",
"[",
"]",
"pattrs",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"(",
"_FORMATTER",
"[",
"x",
".",
"display_group",
"]",
... | 31.6875 | 24 |
def path_components(path):
"""
Return the individual components of a given file path
string (for the local operating system).
Taken from https://stackoverflow.com/q/21498939/438386
"""
components = []
# The loop guarantees that the returned components can be
# os.path.joined with the path separator and point to the same
# location:
while True:
(new_path, tail) = os.path.split(path) # Works on any platform
components.append(tail)
if new_path == path: # Root (including drive, on Windows) reached
break
path = new_path
components.append(new_path)
components.reverse() # First component first
return components | [
"def",
"path_components",
"(",
"path",
")",
":",
"components",
"=",
"[",
"]",
"# The loop guarantees that the returned components can be\r",
"# os.path.joined with the path separator and point to the same\r",
"# location: \r",
"while",
"True",
":",
"(",
"new_path",
",",
"tai... | 36.4 | 17.3 |
def flip_ctrlpts_u(ctrlpts, size_u, size_v):
""" Flips a list of 1-dimensional control points from u-row order to v-row order.
**u-row order**: each row corresponds to a list of u values
**v-row order**: each row corresponds to a list of v values
:param ctrlpts: control points in u-row order
:type ctrlpts: list, tuple
:param size_u: size in u-direction
:type size_u: int
:param size_v: size in v-direction
:type size_v: int
:return: control points in v-row order
:rtype: list
"""
new_ctrlpts = []
for i in range(0, size_u):
for j in range(0, size_v):
temp = [float(c) for c in ctrlpts[i + (j * size_u)]]
new_ctrlpts.append(temp)
return new_ctrlpts | [
"def",
"flip_ctrlpts_u",
"(",
"ctrlpts",
",",
"size_u",
",",
"size_v",
")",
":",
"new_ctrlpts",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"size_u",
")",
":",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"size_v",
")",
":",
"temp",
"="... | 31.434783 | 16.478261 |
def extract_runscript(self):
'''extract the runscript (EntryPoint) as first priority, unless the
user has specified to use the CMD. If Entrypoint is not defined,
we default to None:
1. IF SREGISTRY_DOCKERHUB_CMD is set, use Cmd
2. If not set, or Cmd is None/blank, try Entrypoint
3. If Entrypoint is not set, use default /bin/bash
'''
use_cmd = self._get_setting('SREGISTRY_DOCKER_CMD')
# Does the user want to use the CMD instead of ENTRYPOINT?
commands = ["Entrypoint", "Cmd"]
if use_cmd is not None:
commands.reverse()
# Parse through commands until we hit one
for command in commands:
cmd = self._get_config(command)
if cmd is not None:
break
# Only continue if command still isn't None
if cmd is not None:
bot.verbose3("Adding Docker %s as Singularity runscript..."
% command.upper())
# If the command is a list, join. (eg ['/usr/bin/python','hello.py']
bot.debug(cmd)
if not isinstance(cmd, list):
cmd = [cmd]
cmd = " ".join(['"%s"' % x for x in cmd])
cmd = 'exec %s "$@"' % cmd
cmd = "#!/bin/sh\n\n%s\n" % cmd
return cmd
bot.debug("CMD and ENTRYPOINT not found, skipping runscript.")
return cmd | [
"def",
"extract_runscript",
"(",
"self",
")",
":",
"use_cmd",
"=",
"self",
".",
"_get_setting",
"(",
"'SREGISTRY_DOCKER_CMD'",
")",
"# Does the user want to use the CMD instead of ENTRYPOINT?",
"commands",
"=",
"[",
"\"Entrypoint\"",
",",
"\"Cmd\"",
"]",
"if",
"use_cmd"... | 31.390244 | 21.097561 |
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent} | [
"def",
"diskusage",
"(",
"human_readable",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"path",
"=",
"'c:/'",
"disk_stats",
"=",
"psutil",
".",
"disk_usage",
"(",
"path",
")",
"total_val",
"=",
"disk_stats",
".",
"total",
... | 22.235294 | 19.294118 |
def timebar(t, varname = None, databar = False, delete = False, color = 'black', thick = 1, dash = False):
"""
This function will add a vertical bar to all time series plots. This is useful if you
want to bring attention to a specific time.
Parameters:
t : flt/list
The time in seconds since Jan 01 1970 to place the vertical bar. If a list of numbers are supplied,
multiple bars will be created. If "databar" is set, then "t" becomes the point on the y axis to
place a horizontal bar.
varname : str/list, optional
The variable(s) to add the vertical bar to. If not set, the default is to add it to all current plots.
databar : bool, optional
This will turn the timebar into a horizontal data bar. If this is set True, then variable "t" becomes
the point on the y axis to place a horizontal bar.
delete : bool, optional
If set to True, at lease one varname must be supplied. The timebar at point "t" for variable "varname"
will be removed.
color : str
The color of the bar
thick : int
The thickness of the bar
dash : bool
If set to True, the bar is dashed rather than solid
Returns:
None
Examples:
>>> # Place a green time bar at 2017-07-17 00:00:00
>>> import pytplot
>>> pytplot.timebar(1500249600, color='green')
>>> # Place a dashed data bar at 5500 on the y axis
>>> pytplot.timebar(5500, dashed=True, databar=True)
>>> Place 3 magenta time bars of thickness 5
at [2015-12-26 05:20:01, 2015-12-26 08:06:40, 2015-12-26 08:53:19]
for variable 'sgx' plot
>>> pytplot.timebar([1451107201,1451117200,1451119999],'sgx',color='m',thick=5)
"""
# make sure t entered is a list
if not isinstance(t, list):
t = [t]
#if entries in list not numerical, run str_to_int
if not isinstance(t[0], (int, float, complex)):
t1 = []
for time in t:
t1.append(tplot_utilities.str_to_int(time))
t = t1
dim = 'height'
if databar is True:
dim = 'width'
dash_pattern = 'solid'
if dash is True:
dash_pattern = 'dashed'
if delete is True:
tplot_utilities.timebar_delete(t, varname, dim)
return
#if no varname specified, add timebars to every plot
if varname is None:
num_bars = len(t)
for i in range(num_bars):
tbar = {}
tbar['location'] = t[i]
tbar['dimension'] = dim
tbar['line_color'] = pytplot.tplot_utilities.rgb_color(color)
tbar['line_width'] = thick
tbar['line_dash'] = dash_pattern
for name in data_quants:
temp_data_quants = data_quants[name]
temp_data_quants.time_bar.append(tbar)
#if varname specified
else:
if not isinstance(varname, list):
varname = [varname]
for j in varname:
if j not in data_quants.keys():
print(str(j) + "is currently not in pytplot")
else:
num_bars = len(t)
for i in range(num_bars):
tbar = {}
tbar['location'] = t[i]
tbar['dimension'] = dim
tbar['line_color'] = pytplot.tplot_utilities.rgb_color(color)
tbar['line_width'] = thick
tbar['line_dash'] = dash_pattern
temp_data_quants = data_quants[j]
temp_data_quants.time_bar.append(tbar)
return | [
"def",
"timebar",
"(",
"t",
",",
"varname",
"=",
"None",
",",
"databar",
"=",
"False",
",",
"delete",
"=",
"False",
",",
"color",
"=",
"'black'",
",",
"thick",
"=",
"1",
",",
"dash",
"=",
"False",
")",
":",
"# make sure t entered is a list",
"if",
"not... | 36.99 | 21.73 |
def wait_for_interrupts(threaded=False, epoll_timeout=1):
"""
Blocking loop to listen for GPIO interrupts and distribute them to
associated callbacks. epoll_timeout is an easy way to shutdown the
blocking function. Per default the timeout is set to 1 second; if
`_is_waiting_for_interrupts` is set to False the loop will exit.
If an exception occurs while waiting for interrupts, the interrupt
gpio interfaces will be cleaned up (/sys/class/gpio unexports). In
this case all interrupts will be reset and you'd need to add the
callbacks again before using `wait_for_interrupts(..)` again.
If the argument `threaded` is True, wait_for_interrupts will be
started in a daemon Thread. To quit it, call
`RPIO.stop_waiting_for_interrupts()`.
"""
if threaded:
t = Thread(target=_rpio.wait_for_interrupts, args=(epoll_timeout,))
t.daemon = True
t.start()
else:
_rpio.wait_for_interrupts(epoll_timeout) | [
"def",
"wait_for_interrupts",
"(",
"threaded",
"=",
"False",
",",
"epoll_timeout",
"=",
"1",
")",
":",
"if",
"threaded",
":",
"t",
"=",
"Thread",
"(",
"target",
"=",
"_rpio",
".",
"wait_for_interrupts",
",",
"args",
"=",
"(",
"epoll_timeout",
",",
")",
"... | 43.863636 | 22.772727 |
def auto_create_version(class_name, version, filename="__init__.py"):
"""
creates a version number in the __init__.py file.
it can be accessed with __version__
:param class_name:
:param version:
:param filename:
:return:
"""
version_filename = Path(
"{classname}/{filename}".format(classname=class_name,
filename=filename))
with open(version_filename, "r") as f:
content = f.read()
if content != '__version__ = "{0}"'.format(version):
banner("Updating version to {0}".format(version))
with open(version_filename, "w") as text_file:
text_file.write('__version__ = "{0:s}"'.format(version)) | [
"def",
"auto_create_version",
"(",
"class_name",
",",
"version",
",",
"filename",
"=",
"\"__init__.py\"",
")",
":",
"version_filename",
"=",
"Path",
"(",
"\"{classname}/{filename}\"",
".",
"format",
"(",
"classname",
"=",
"class_name",
",",
"filename",
"=",
"filen... | 37 | 16.263158 |
def _walk_factory(self, dep_predicate):
"""Construct the right context object for managing state during a transitive walk."""
walk = None
if dep_predicate:
walk = self.DepPredicateWalk(dep_predicate)
else:
walk = self.NoDepPredicateWalk()
return walk | [
"def",
"_walk_factory",
"(",
"self",
",",
"dep_predicate",
")",
":",
"walk",
"=",
"None",
"if",
"dep_predicate",
":",
"walk",
"=",
"self",
".",
"DepPredicateWalk",
"(",
"dep_predicate",
")",
"else",
":",
"walk",
"=",
"self",
".",
"NoDepPredicateWalk",
"(",
... | 34.375 | 14 |
def write_config(self):
""" Write config to file """
if not os.path.exists(os.path.dirname(self.config_file)):
os.makedirs(os.path.dirname(self.config_file))
with open(self.config_file, 'w') as f:
f.write(json.dumps(self.config))
f.close() | [
"def",
"write_config",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"config_file",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(... | 41.857143 | 12.714286 |
def removeforkrelation(self, project_id):
"""
Remove an existing fork relation. this DO NOT remove the fork,only the relation between them
:param project_id: project id
:return: true if success
"""
request = requests.delete(
'{0}/{1}/fork'.format(self.projects_url, project_id),
headers=self.headers, verify=self.verify_ssl,
auth=self.auth, timeout=self.timeout)
if request.status_code == 200:
return True
else:
return False | [
"def",
"removeforkrelation",
"(",
"self",
",",
"project_id",
")",
":",
"request",
"=",
"requests",
".",
"delete",
"(",
"'{0}/{1}/fork'",
".",
"format",
"(",
"self",
".",
"projects_url",
",",
"project_id",
")",
",",
"headers",
"=",
"self",
".",
"headers",
"... | 33.4375 | 16.9375 |
def action_update(self):
"""Form action enpoint to update the attachments
"""
order = []
form = self.request.form
attachments = form.get("attachments", [])
for attachment in attachments:
# attachment is a form mapping, not a dictionary -> convert
values = dict(attachment)
uid = values.pop("UID")
obj = api.get_object_by_uid(uid)
# delete the attachment if the delete flag is true
if values.pop("delete", False):
self.delete_attachment(obj)
continue
# remember the order
order.append(uid)
# update the attachment with the given data
obj.update(**values)
obj.reindexObject()
# set the attachments order to the annotation storage
self.set_attachments_order(order)
# redirect back to the default view
return self.request.response.redirect(self.context.absolute_url()) | [
"def",
"action_update",
"(",
"self",
")",
":",
"order",
"=",
"[",
"]",
"form",
"=",
"self",
".",
"request",
".",
"form",
"attachments",
"=",
"form",
".",
"get",
"(",
"\"attachments\"",
",",
"[",
"]",
")",
"for",
"attachment",
"in",
"attachments",
":",
... | 30.78125 | 17.9375 |
def _fix_tagging(value, params):
"""
Checks if a value is properly tagged based on the spec, and re/untags as
necessary
:param value:
An Asn1Value object
:param params:
A dict of spec params
:return:
An Asn1Value that is properly tagged
"""
_tag_type_to_explicit_implicit(params)
retag = False
if 'implicit' not in params:
if value.implicit is not False:
retag = True
else:
if isinstance(params['implicit'], tuple):
class_, tag = params['implicit']
else:
tag = params['implicit']
class_ = 'context'
if value.implicit is False:
retag = True
elif value.class_ != CLASS_NAME_TO_NUM_MAP[class_] or value.tag != tag:
retag = True
if params.get('explicit') != value.explicit:
retag = True
if retag:
return value.retag(params)
return value | [
"def",
"_fix_tagging",
"(",
"value",
",",
"params",
")",
":",
"_tag_type_to_explicit_implicit",
"(",
"params",
")",
"retag",
"=",
"False",
"if",
"'implicit'",
"not",
"in",
"params",
":",
"if",
"value",
".",
"implicit",
"is",
"not",
"False",
":",
"retag",
"... | 23.947368 | 19.684211 |
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
self.ready = False
if self._start_time is not None:
self._run_time += (time.time() - self._start_time)
self._start_time = None
sock = getattr(self, 'socket', None)
if sock:
if not isinstance(self.bind_addr, six.string_types):
# Touch our own socket to make accept() return immediately.
try:
host, port = sock.getsockname()[:2]
except socket.error as ex:
if ex.args[0] not in errors.socket_errors_to_ignore:
# Changed to use error code and not message
# See
# https://github.com/cherrypy/cherrypy/issues/860.
raise
else:
# Note that we're explicitly NOT using AI_PASSIVE,
# here, because we want an actual IP to touch.
# localhost won't work if we've bound to a public IP,
# but it will if we bound to '0.0.0.0' (INADDR_ANY).
for res in socket.getaddrinfo(
host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM,
):
af, socktype, proto, canonname, sa = res
s = None
try:
s = socket.socket(af, socktype, proto)
# See
# https://groups.google.com/group/cherrypy-users/
# browse_frm/thread/bbfe5eb39c904fe0
s.settimeout(1.0)
s.connect((host, port))
s.close()
except socket.error:
if s:
s.close()
if hasattr(sock, 'close'):
sock.close()
self.socket = None
self.requests.stop(self.shutdown_timeout) | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"ready",
"=",
"False",
"if",
"self",
".",
"_start_time",
"is",
"not",
"None",
":",
"self",
".",
"_run_time",
"+=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_start_time",
")",
"self",
... | 44.826087 | 16.934783 |
def parse_date(value):
"""Attempts to parse `value` into an instance of ``datetime.date``. If
`value` is ``None``, this function will return ``None``.
Args:
value: A timestamp. This can be a string, datetime.date, or
datetime.datetime value.
"""
if not value:
return None
if isinstance(value, datetime.date):
return value
return parse_datetime(value).date() | [
"def",
"parse_date",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"date",
")",
":",
"return",
"value",
"return",
"parse_datetime",
"(",
"value",
")",
".",
"date",
"(",
")"
... | 25.625 | 20.3125 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.