code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if result is None:
return
elif isinstance(result, basestring):
pass
elif isinstance(result, collections.Mapping):
result = u'\n'.join(u'%s=%s' % (k, v) for
k, v in result.iteritems() if v is not None)
elif isinstance(result, collections.Iterable):... | def display(result, stream) | Intelligently print the result (or pass if result is None).
:param result:
:return: None | 2.192022 | 2.228624 | 0.983577 |
while True:
try:
return eval(command, glob, local)
except NameError as e:
match = re.match("name '(.*)' is not defined", e.message)
if not match:
raise e
try:
exec ('import %s' % (match.group(1), )) in glob
... | def safe_evaluate(command, glob, local) | Continue to attempt to execute the given command, importing objects which
cause a NameError in the command
:param command: command for eval
:param glob: globals dict for eval
:param local: locals dict for eval
:return: command result | 2.731048 | 3.062742 | 0.8917 |
# 1. Lookup in specials
if num in specialnumbers['specials']:
retval = specialnumbers['specials'][num]
return _add_gershayim(retval) if gershayim else retval
# 2. Generate numeral normally
parts = []
rest = str(num)
while rest:
digit = int(rest[0])
rest = re... | def int_to_gematria(num, gershayim=True) | convert integers between 1 an 999 to Hebrew numerals.
- set gershayim flag to False to ommit gershayim | 3.56388 | 3.641059 | 0.978803 |
html = requests.get(onetab).text
soup = BeautifulSoup(html, 'lxml')
divs = soup.findAll('div', {'style': 'padding-left: 24px; '
'padding-top: 8px; '
'position: relative; '
'font-s... | def get_urls_from_onetab(onetab) | Get video urls from a link to the onetab shared page.
Args:
onetab (str): Link to a onetab shared page.
Returns:
list: List of links to the videos. | 2.747586 | 2.84174 | 0.966868 |
stats = []
for (filename, lineno, name), stat_values in d.iteritems():
if len(stat_values) == 5:
ncalls, ncall_nr, total_time, cum_time, subcall_stats = stat_values
else:
ncalls, ncall_nr, total_time, cum_time = stat_values
... | def from_dict(cls, d) | Used to create an instance of this class from a pstats dict item | 3.17042 | 2.832118 | 1.119452 |
if self.subcall is not None:
if isinstance(self.subcall, dict):
subcalls = self.subcall
else:
subcalls = {}
for s in self.subcall:
subcalls.update(s.to_dict())
return {(self.filename, self.line_numbe... | def to_dict(self) | Convert back to the pstats dictionary representation (used for saving back as pstats binary file) | 2.819747 | 2.498693 | 1.128489 |
for f in funcs:
f.exclude = True
run_time_s = sum(0 if s.exclude else s.own_time_s for s in self.stats)
cProfileFuncStat.run_time_s = run_time_s | def exclude_functions(self, *funcs) | Excludes the contributions from the following functions. | 8.12058 | 8.334256 | 0.974362 |
return sorted(self.stats, key=lambda x: getattr(x, stat), reverse=True)[:n] | def get_top(self, stat, n) | Return the top n values when sorting by 'stat | 3.84603 | 3.485188 | 1.103536 |
stats = {}
for s in self.stats:
if not s.exclude:
stats.update(s.to_dict())
with open(path, 'wb') as f:
marshal.dump(stats, f) | def save_pstat(self, path) | Save the modified pstats file | 3.748329 | 3.628594 | 1.032998 |
try:
result = int(value)
if result < 0:
raise NegativeDurationError(
'Negative values in duration strings are not allowed!'
)
except NegativeDurationError as exc:
raise exc
except (TypeError, ValueError):
result = 0
return resu... | def safe_int(value) | Tries to convert a value to int; returns 0 if conversion failed | 4.170296 | 4.011913 | 1.039478 |
pattern = r'(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)'
match = re.match(pattern, value)
if not match:
raise ValueError('Invalid duration value: %s' % value)
hours = safe_int(match.group('hours'))
minutes = safe_int(match.group('minutes'))
seconds = safe_int(match.group('... | def _parse(value, strict=True) | Preliminary duration value parser
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values | 2.345291 | 2.203833 | 1.064187 |
# split seconds to larger units
# seconds = value.total_seconds()
seconds = to_seconds(value, strict, force_int)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
days, hours, minutes = map(int, (days, hours, minutes))
secon... | def to_iso8601(value, strict=True, force_int=True) | converts duration value to ISO8601 string
accepts integers, hh:mm:ss or mm:ss strings, timedelta objects
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration string exceed allowed values | 2.882375 | 3.103484 | 0.928755 |
if isinstance(value, int):
return value # assuming it's seconds
elif isinstance(value, timedelta):
seconds = value.total_seconds()
if force_int:
seconds = int(round(seconds))
return seconds
elif isinstance(value, str):
hours, minutes, seconds = _pars... | def to_seconds(value, strict=True, force_int=True) | converts duration value to integer seconds
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values | 2.474289 | 2.637024 | 0.938288 |
if isinstance(value, int):
return timedelta(seconds=value) # assuming it's seconds
elif isinstance(value, timedelta):
return value
elif isinstance(value, str):
hours, minutes, seconds = _parse(value, strict)
elif isinstance(value, tuple):
check_tuple(value, strict)
... | def to_timedelta(value, strict=True) | converts duration string to timedelta
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration string exceed allowed values | 2.517005 | 2.678591 | 0.939675 |
if isinstance(value, int):
seconds = value
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
elif isinstance(value, str):
hours, minutes, seconds = _fix_tuple(
_parse(value, strict)
)
elif isinstance(value, tuple):
ch... | def to_tuple(value, strict=True, force_int=True) | converts duration value to tuple of integers
strict=True (by default) raises StrictnessError if either hours,
minutes or seconds in duration value exceed allowed values | 2.167573 | 2.184356 | 0.992317 |
snake_parts = method_name.split('_')
if len(snake_parts) <= 1:
return False
# Convention for libcloud is ex_ are extended methods
if snake_parts[0] == 'ex':
extra = True
method_name = method_name.replace('ex_', '', 1)
else:
extra = False
snake_parts = method... | def name_url(provider, cloud, method_name) | Get a URL for a method in a driver | 3.693866 | 3.676519 | 1.004718 |
if len(data) < 2:
return False
b2 = struct.unpack('!B', data[1])[0]
payload_len = b2 & 0x7F
payload_start = 2
if payload_len == 126:
if len(data) > 4:
payload_len = struct.unpack('!H', data[2:4])[0]
payload_start = 4
elif payload_len == 127:
if... | def contains_frame(data) | Read the frame length from the start of `data` and check if the data is
long enough to contain the entire frame. | 2.180591 | 2.082814 | 1.046944 |
if len(key) != 4:
raise ValueError('invalid masking key "%s"' % key)
key = map(ord, key)
masked = bytearray(original)
for i in xrange(len(masked)):
masked[i] ^= key[i % 4]
return masked | def mask(key, original) | Mask an octet string using the given masking key.
The following masking algorithm is used, as defined in RFC 6455:
for each octet:
j = i MOD 4
transformed-octet-i = original-octet-i XOR masking-key-octet-j | 2.879747 | 3.351681 | 0.859195 |
header = struct.pack('!B', (self.final << 7) | (self.rsv1 << 6)
| (self.rsv2 << 5) | (self.rsv3 << 4)
| (self.opcode & 0xf))
mask = bool(self.masking_key) << 7
payload_len = len(self.payload)
if payload_len <... | def pack(self) | Pack the frame into a string according to the following scheme:
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| ... | 2.504621 | 2.612013 | 0.958885 |
frames = []
for start in xrange(0, len(self.payload), fragment_size):
payload = self.payload[start:start + fragment_size]
frames.append(Frame(OPCODE_CONTINUATION, payload, mask=mask,
final=False))
frames[0].opcode = self.opcode
... | def fragment(self, fragment_size, mask=False) | Fragment the frame into a chain of fragment frames:
- An initial frame with non-zero opcode
- Zero or more frames with opcode = 0 and final = False
- A final frame with opcode = 0 and final = True
The first and last frame may be the same frame, having a non-zero
opcode and final... | 3.783851 | 3.092259 | 1.223653 |
if self.payload:
code = struct.unpack('!H', str(self.payload[:2]))[0]
reason = str(self.payload[2:])
else:
code = None
reason = ''
return code, reason | def unpack_close(self) | Unpack a close message into a status code and a reason. If no payload
is given, the code is None and the reason is an empty string. | 3.217886 | 2.284791 | 1.408394 |
data = ''
while len(data) < n:
received = self.sock.recv(n - len(data))
if not len(received):
raise socket.error('no data read from socket')
data += received
return data | def readn(self, n) | Keep receiving data until exactly `n` bytes have been read. | 3.103117 | 2.698779 | 1.149823 |
def parse_resolution(res: str) -> Tuple[int, ...]:
return tuple(map(int, res.split('x')))
raw_resolution = video_data['resolution']
resolution = parse_resolution(raw_resolution)
return resolution | def quality_comparator(video_data) | Custom comparator used to choose the right format based on the resolution. | 3.821347 | 3.433523 | 1.112952 |
if target_info is not None and target_info[TargetInfo.NTLMSSP_AV_FLAGS] is not None:
flags = struct.unpack('<I', target_info[TargetInfo.NTLMSSP_AV_FLAGS][1])[0]
return bool(flags & 0x00000002) | def _mic_required(target_info) | Checks the MsvAvFlags field of the supplied TargetInfo structure to determine in the MIC flags is set
:param target_info: The TargetInfo structure to check
:return: a boolean value indicating that the MIC flag is set | 3.716082 | 3.034097 | 1.224773 |
# Generate the NTLM Negotiate Request
negotiate_token = self._negotiate(self.flags)
challenge_token = yield negotiate_token
# Generate the Authenticate Response
authenticate_token = self._challenge_response(negotiate_token, challenge_token)
yield authenticate_to... | def initialize_security_context(self) | Idiomatic Python implementation of initialize_security_context, implemented as a generator function using
yield to both accept incoming and return outgoing authentication tokens
:return: The response to be returned to the server | 5.802422 | 5.401715 | 1.074181 |
if not self.is_established:
raise Exception("Context has not been established")
if self._wrapper is None:
raise Exception("Neither sealing or signing have been negotiated")
else:
return self._wrapper.wrap(message) | def wrap_message(self, message) | Cryptographically signs and optionally encrypts the supplied message. The message is only encrypted if
'confidentiality' was negotiated, otherwise the message is left untouched.
:return: A tuple containing the message signature and the optionally encrypted message | 6.100989 | 5.878223 | 1.037897 |
if not self.is_established:
raise Exception("Context has not been established")
if self._wrapper is None:
raise Exception("Neither sealing or signing have been negotiated")
else:
return self._wrapper.unwrap(message, signature) | def unwrap_message(self, message, signature) | Verifies the supplied signature against the message and decrypts the message if 'confidentiality' was
negotiated.
A SignatureException is raised if the signature cannot be parsed or the version is unsupported
A SequenceException is raised if the sequence number in the signature is incorrect
... | 5.807821 | 5.802585 | 1.000902 |
parser = argparse.ArgumentParser(description='Video downloader by radzak.',
prog='RTVdownloader')
urls_group = parser.add_mutually_exclusive_group(required=True)
urls_group.add_argument('urls',
type=str,
metava... | def parse_options() | Parse command line arguments.
Returns:
options, args | 4.074907 | 4.045794 | 1.007196 |
html = requests.get(self.url).text
soup = BeautifulSoup(html, 'lxml')
div = soup.find('div', class_='more-back')
if div:
parsed_uri = urlparse(self.url)
domain = '{uri.scheme}://{uri.netloc}'.format(uri=parsed_uri)
suffix = div.find('a', href... | def get_article_url(self) | Get the url of the TVP Info article itself, not the url of the preview with
the 'Przejdź do artykułu' hyperlink.
Returns:
(str): Url of the article with the video. | 2.685709 | 2.877272 | 0.933422 |
self.split_scheme = dict()
if isinstance(X, pd.DataFrame):
# self.indx = X.index
# self.columns = X.columns
if isinstance(self._features, list):
self.categorical = [X.columns.get_loc(label) for label in self._features]
X = X.value... | def fit(self, X, y) | Fit CAIM
Parameters
----------
X : array-like, pandas dataframe, shape [n_samples, n_feature]
Input array can contain missing values
y: array-like, pandas dataframe, shape [n_samples]
Target variable. Must be categorical.
Returns
-------
s... | 3.505424 | 3.47521 | 1.008694 |
if isinstance(X, pd.DataFrame):
self.indx = X.index
self.columns = X.columns
X = X.values
X_di = X.copy()
categorical = self.categorical
scheme = self.split_scheme
for j in range(X.shape[1]):
if j in categorical:
... | def transform(self, X) | Discretize X using a split scheme obtained with CAIM.
Parameters
----------
X : array-like or pandas dataframe, shape [n_samples, n_features]
Input array can contain missing values
Returns
-------
X_di : sparse matrix if sparse=True else a 2-d array, dtype=int... | 3.030644 | 2.72899 | 1.110537 |
'Clean (and optionally escape) passed html of unsafe tags and attributes.'
value = html_cleaner(value)
return escape(value) if autoescape\
and not isinstance(value, SafeData) else mark_safe(value) | def prettyhtml(value, autoescape=None) | Clean (and optionally escape) passed html of unsafe tags and attributes. | 8.927618 | 4.420331 | 2.019672 |
'Get N chars (default: all) of secure hash hexdigest of value.'
value = hash_func(value).hexdigest()
if chars: value = value[:chars]
return mark_safe(value) | def hash(value, chars=None) | Get N chars (default: all) of secure hash hexdigest of value. | 9.385863 | 3.84074 | 2.443764 |
# interpolate wd noise
amp_n_wd_interp = interpolate.interp1d(f_n_wd, amp_n_wd, bounds_error=False, fill_value=1e-30)
# find points of wd noise amplitude at noise curve frequencies
amp_n_wd = amp_n_wd_interp(f_n)
# keep the greater value at each frequency
amp_n = amp_n*(amp_n >= amp_n_wd... | def combine_with_wd_noise(f_n, amp_n, f_n_wd, amp_n_wd) | Combine noise with wd noise.
Combines noise and white dwarf background noise based on greater
amplitude value at each noise curve step.
Args:
f_n (float array): Frequencies of noise curve.
amp_n (float array): Amplitude values of noise curve.
f_n_wd (float array): Frequencies of wd... | 3.224623 | 2.998075 | 1.075565 |
if return_curves is False and print_curves is False:
raise ValueError("Both return curves and print_curves are False."
+ " You will not see the options")
cfd = os.path.dirname(os.path.abspath(__file__))
curves = [curve.split('.')[0] for curve in os.listdir(cfd + '/noise... | def show_available_noise_curves(return_curves=True, print_curves=False) | List available sensitivity curves
This function lists the available sensitivity curve strings in noise_curves folder.
Args:
return_curves (bool, optional): If True, return a list of curve options.
print_curves (bool, optional): If True, print each curve option.
Returns:
(optional ... | 3.636766 | 3.726496 | 0.975921 |
from functools import reduce
curleys = list(re.finditer(r"{[^{}]*}", s))
return reduce(_replace_curly, reversed(curleys), [s]) | def expand_curlys(s) | Takes string and returns list of options:
Example
-------
>>> expand_curlys("py{26, 27}")
["py26", "py27"] | 7.367943 | 8.278983 | 0.889958 |
prev = 0
for m in re.finditer(r"{[^{}]*}|\s*,\s*", s):
if not m.group().startswith("{"):
part = s[prev:m.start()]
if part:
yield s[prev:m.start()]
prev = m.end()
part = s[prev:]
if part:
yield part | def _split_out_of_braces(s) | Generator to split comma seperated string, but not split commas inside
curly braces.
>>> list(_split_out_of_braces("py{26, 27}-django{15, 16}, py32"))
>>>['py{26, 27}-django{15, 16}, py32'] | 2.844375 | 3.135958 | 0.907019 |
try:
factor, value = re.split(r'\s*\:\s*', s)
except ValueError:
return s
if matches_factor_conditions(factor, env):
return value
else:
return '' | def expand_factor_conditions(s, env) | If env matches the expanded factor then return value else return ''.
Example
-------
>>> s = 'py{33,34}: docformatter'
>>> expand_factor_conditions(s, Env(name="py34", ...))
"docformatter"
>>> expand_factor_conditions(s, Env(name="py26", ...))
"" | 5.242454 | 4.76034 | 1.101277 |
env_labels = set(env.name.split('-'))
labels = set(bash_expand(s))
return bool(labels & env_labels) | def matches_factor_conditions(s, env) | Returns True if py{33, 34} expanded is contained in env.name. | 9.364303 | 6.760736 | 1.385101 |
pattern = '''((?:[^%s"']|"[^"]*"|'[^']*')+)''' % sep
return [_strip_speechmarks(t) for t in re.split(pattern, s)[1::2]] | def split_on(s, sep=" ") | Split s by sep, unless it's inside a quote. | 7.178398 | 6.648234 | 1.079745 |
def replace(m):
return _replace_match(m, env)
for _ in range(DEPTH):
s = re.sub(r"{[^{}]*}", replace, s)
return s | def replace_braces(s, env) | Makes tox substitutions to s, with respect to environment env.
Example
-------
>>> replace_braces("echo {posargs:{env:USER:} passed no posargs}")
"echo andy passed no posargs"
Note: first "{env:USER:}" is replaced with os.environ.get("USER", ""),
the "{posargs:andy}" is replaced with "andy" (s... | 4.911618 | 7.3779 | 0.66572 |
# ditch the curly braces
s = m.group()[1:-1].strip()
try:
# get the env attributes e.g. envpython or toxinidir.
# Note: if you ask for a env methodname this will raise
# later on... so don't do that.
return getattr(env, s)
except AttributeError:
pass
fo... | def _replace_match(m, env) | Given a match object, having matched something inside curly braces,
replace the contents if matches one of the supported tox-substitutions. | 10.000745 | 8.232062 | 1.214853 |
e = s.split(":")
if len(e) > 3 or len(e) == 1 or e[0] != "env":
raise ValueError()
elif len(e) == 2:
# Note: this can/should raise a KeyError (according to spec).
return os.environ[e[1]]
else: # len(e) == 3
return os.environ.get(e[1], e[2]) | def _replace_envvar(s, _) | env:KEY or env:KEY:DEFAULT | 3.660399 | 3.206612 | 1.141516 |
m = re.match(r"\[(.*?)\](.*)", s)
if m:
section, option = m.groups()
expanded = env.config.get(section, option)
return '\n'.join([expand_factor_conditions(e, env)
for e in expanded.split("\n")])
else:
raise ValueError() | def _replace_config(s, env) | [sectionname]optionname | 4.759498 | 4.501526 | 1.057308 |
"posargs:DEFAULT"
e = re.split(r'\s*\:\s*', s)
if e and e[0] == "posargs":
from ctox.main import positional_args
return (" ".join(positional_args(env.options)) or
(e[1] if len(e) > 1 else ""))
else:
raise ValueError() | def _replace_posargs(s, env) | posargs:DEFAULT | 7.886564 | 6.27184 | 1.257456 |
if len(Mt.shape)==2: _Mt = Mt[:, :, sp.newaxis]
else: _Mt = Mt
LMt = vei_CoR_veX(_Mt, R=self.Lr(), C=self.Lc())
DMt = self.D()[:, :, sp.newaxis] * LMt
WrDMtWc = vei_CoR_veX(DMt, R=self.Wr().T, C=self.Wc().T)
ve_WrDMtWc = sp.reshape(WrDMtWc, (... | def solve_t(self, Mt) | Mt is dim_r x dim_c x d tensor | 3.379859 | 3.314657 | 1.019671 |
DMt = self.D()[:, :, sp.newaxis] * Mt
WrDMtWc = vei_CoR_veX(DMt, R=self.Wr().T, C=self.Wc().T)
ve_WrDMtWc = sp.reshape(WrDMtWc, (WrDMtWc.shape[0] * WrDMtWc.shape[1], Mt.shape[2]), order='F')
Hi_ve_WrDMtWc = la.cho_solve((self.H_chol(), True), ve_WrDMtWc)
vei_HiveWrDMtWc ... | def _O_dot(self, Mt) | Mt is dim_r x dim_c x d tensor | 4.115236 | 4.095691 | 1.004772 |
self._A = []
self._F = []
self._B = []
self._A_identity = []
self._REML_term = []
self._n_terms = 0
self._n_fixed_effs = 0
self._n_fixed_effs_REML = 0
self.indicator = {'term':np.array([]),
'row':np.array([]),
... | def clearFixedEffect(self) | erase all fixed effects | 8.335223 | 8.044454 | 1.036145 |
if F is None: F = np.ones((self.N,1))
if A is None:
A = np.eye(self.P)
A_identity = True
elif (A.shape == (self.P,self.P)) & (A==np.eye(self.P)).all():
A_identity = True
else:
A_identity = False
assert F.shape[0]==self.N... | def addFixedEffect(self,F=None,A=None, REML=True, index=None) | set sample and trait designs
F: NxK sample design
A: LxP sample design
REML: REML for this term?
index: index of which fixed effect to replace. If None, just append. | 2.944518 | 2.868254 | 1.026589 |
if self._n_terms==0:
pass
if index is None or index==(self._n_terms-1):
self._n_terms-=1
F = self._F.pop() #= self.F[:-1]
A = self._A.pop() #= self.A[:-1]
self._A_identity.pop() #= self.A_identity[:-1]
REML_term = self._RE... | def removeFixedEffect(self, index=None) | set sample and trait designs
F: NxK sample design
A: LxP sample design
REML: REML for this term?
index: index of which fixed effect to replace. If None, remove last term. | 5.614026 | 5.137432 | 1.092769 |
self._N,self._P = value.shape
self._Y = value
self.clear_cache('Ystar1','Ystar','Yhat','LRLdiag_Yhat',
'beta_grad','Xstar_beta_grad','Zstar','DLZ') | def Y(self,value) | set phenotype | 18.517635 | 18.163006 | 1.019525 |
assert value.shape[0]==self._N, 'dimension mismatch'
assert value.shape[1]==self._N, 'dimension mismatch'
self._Lr = value
self.clear_cache('Fstar','Ystar1','Ystar','Yhat','Xstar','Xhat',
'Areml','Areml_eigh','Areml_chol','Areml_inv','beta_hat','B_hat',
... | def Lr(self,value) | set row rotation | 6.334955 | 6.509614 | 0.973169 |
assert value.shape[0]==self._P, 'Lc dimension mismatch'
assert value.shape[1]==self._P, 'Lc dimension mismatch'
self._Lc = value
self.clear_cache('Astar','Ystar','Yhat','Xstar','Xhat',
'Areml','Areml_eigh','Areml_chol','Areml_inv','beta_hat','B_hat',
... | def Lc(self,value) | set col rotation | 9.272196 | 9.889342 | 0.937595 |
assert value.shape[0]==self._P*self._N, 'd dimension mismatch'
self._d = value
self.clear_cache('Yhat','Xhat','Areml','Areml_eigh','Areml_chol','Areml_inv','beta_hat','B_hat',
'LRLdiag_Xhat_tens','LRLdiag_Yhat','Areml_grad',
'beta_grad',... | def d(self,value) | set anisotropic scaling | 12.945684 | 13.349613 | 0.969742 |
RV = self.Ystar().copy()
for term_i in range(self.n_terms):
if self.identity_trick and self.A_identity[term_i]:
RV-=np.dot(self.Fstar()[term_i],self.B_hat()[term_i])
else:
RV-=np.dot(self.Fstar()[term_i],np.dot(self.B_hat()[term_i],self.As... | def Zstar(self) | predict the value of the fixed effect | 4.507141 | 4.319792 | 1.04337 |
s,U = LA.eigh(self.Areml(),lower=True)
i_pos = (s>1e-10)
s = s[i_pos]
U = U[:,i_pos]
return s,U | def Areml_eigh(self) | compute the eigenvalue decomposition of Astar | 4.023637 | 3.711023 | 1.084239 |
RV = np.zeros((self.N,self.P))
for term_i in range(self.n_terms):
RV+=np.dot(self.Fstar()[term_i],np.dot(self.B()[term_i],self.Astar()[term_i]))
return RV | def predict(self) | predict the value of the fixed effect | 5.069907 | 4.661868 | 1.087527 |
i = int(self.indicator['term'][j])
r = int(self.indicator['row'][j])
c = int(self.indicator['col'][j])
rv = -np.kron(self.Fstar()[i][:,[r]],self.Astar()[i][[c],:])
return rv | def getGradient(self,j) | get rotated gradient for fixed effect i | 6.908254 | 6.312514 | 1.094374 |
if 0:
#TODO: implement this properly
pass
else:
RV = np.dot(self.Xstar().T,M)
return RV | def XstarT_dot(self,M) | get dot product of Xhat and M | 6.236645 | 6.139613 | 1.015804 |
X = np.zeros((self.N*self.P,self.n_fixed_effs))
ip = 0
for i in range(self.n_terms):
Ki = self.A[i].shape[0]*self.F[i].shape[1]
X[:,ip:ip+Ki] = np.kron(self.A[i].T,self.F[i])
ip += Ki
y = np.reshape(self.Y,(self.Y.size,1),order='F')
RV... | def getResiduals(self) | regress out fixed effects and results residuals | 3.568408 | 3.180877 | 1.121831 |
rv = np.array([])
if self.n_terms>0:
rv = np.concatenate([np.reshape(self.B[term_i],self.B[term_i].size, order='F') for term_i in range(self.n_terms)])
return rv | def getParams(self) | get params | 4.445632 | 4.230208 | 1.050925 |
start = 0
for i in range(self.n_terms):
n_effects = self.B[i].size
self.B[i] = np.reshape(params[start:start+n_effects],self.B[i].shape, order='F')
start += n_effects | def setParams(self,params) | set params | 3.466206 | 3.52449 | 0.983463 |
for key in list(x.keys()):
self.toChange[key] = True | def _set_toChange(x) | set variables in list x toChange | 6.27296 | 5.665257 | 1.107268 |
_update = {'term': self.n_terms*np.ones((K,L)).T.ravel(),
'row': np.kron(np.arange(K)[:,np.newaxis],np.ones((1,L))).T.ravel(),
'col': np.kron(np.ones((K,1)),np.arange(L)[np.newaxis,:]).T.ravel()}
for key in list(_update.keys()):
self.indicator... | def _update_indicator(self,K,L) | update the indicator | 2.793731 | 2.752804 | 1.014867 |
indicator = {'term':np.array([]),
'row':np.array([]),
'col':np.array([])}
for term in range(self.n_terms):
L = self.A[term].shape[0]
K = self.F[term].shape[1]
_update = {'term': (term+1)*np.ones((K,L)).T.ravel(),
... | def _rebuild_indicator(self) | update the indicator | 2.968988 | 2.87264 | 1.03354 |
_X = X.transpose((0,2,1))
if R is not None: RV = sp.tensordot(R, _X, (1,0))
else: RV = _X
if C is not None: RV = sp.dot(RV, C.T)
return RV.transpose((0,2,1)) | def vei_CoR_veX(X, C=None, R=None) | Args:
X: NxPxS tensor
C: CxC row covariance (if None: C set to I_PP)
R: NxN row covariance (if None: R set to I_NN)
Returns:
NxPxS tensor obtained as ve^{-1}((C \kron R) ve(X))
where ve(X) reshapes X as a NPxS matrix. | 3.088177 | 3.269756 | 0.944467 |
# Create the pygame surface
self.shades[shade_name] = [0, pygame.Surface(self.image.get_size())]
# Fill the surface with a solid color or an image
if type(shade_color) == str:
background = pygame.image.load(shade_color).convert()
background = pygame.tra... | def initialize_shade(self, shade_name, shade_color, alpha) | This method will create semi-transparent surfaces with a specified
color. The surface can be toggled on and off.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Inputs:
Shade_name - String of the name that you want to associate with the
surfac... | 2.384482 | 2.416325 | 0.986822 |
# First toggle the user specified shade
if self.shades[shade][0]:
self.shades[shade][0] = 0
else:
self.shades[shade][0] = 1
# Now draw the image with the active shades
self.image.blit(self.pic, (0, 0))
for key in self.shades:
... | def toggle_shade(self, shade) | This method will overlay a semi-transparent shade on top of the
tile's image.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Inputs:
shade - This will designate which shade you wish to turn on or off.
Blue and red shades are available by defa... | 2.739614 | 2.685759 | 1.020052 |
# Initialize the list of tiles to return
adj_tiles = []
# Find the row and column of the input tile
for i in self:
for j in i:
if j == tile:
row = self.index(i)
column = sel... | def adjacent_tiles(self, tile, pattern) | This will return a list of the tiles adjacent to a given tile.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Inputs:
tile - This is the tile object for which the method will find
adjacent tiles.
pattern - This will d... | 1.89029 | 1.711689 | 1.104342 |
ptg.BaseScreen.set_offset(self, offset, mid)
for i in self.tilelist:
for j in i:
j.rect[0] += offset[0]
j.rect[1] += offset[1] | def set_offset(self, offset, mid=None) | This method will allow the menu to be placed anywhere in the open
window instead of just the upper left corner.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Inputs:
offset - This is the x,y tuple of the position that you want to
move the... | 5.32162 | 4.812401 | 1.105814 |
if hasattr(stream, "read"):
return bdecode(stream.read())
else:
handle = open(stream, "rb")
try:
return bdecode(handle.read())
finally:
handle.close() | def bread(stream) | Decode a file or stream to an object. | 2.685232 | 2.302232 | 1.16636 |
handle = None
if not hasattr(stream, "write"):
stream = handle = open(stream, "wb")
try:
stream.write(bencode(obj))
finally:
if handle:
handle.close() | def bwrite(stream, obj) | Encode a given object to a file or stream. | 3.181044 | 2.90598 | 1.094655 |
kind = self.data[self.offset]
except IndexError:
raise BencodeError("Unexpected end of data at offset %d/%d" % (
self.offset, len(self.data),
))
if kind.isdigit():
# String
try:
end = self.data.find(':', self.of... | def decode(self, check_trailer=False): # pylint: disable=I0011,R0912
try | Decode data in C{self.data} and return deserialized object.
@param check_trailer: Raise error if trailing junk is found in data?
@raise BencodeError: Invalid data. | 1.889138 | 1.883841 | 1.002812 |
if isinstance(obj, int_like_types):
self.result.append("i%de" % obj)
elif isinstance(obj, string_types):
self.result.extend([str(len(obj)), ':', str(obj)])
elif hasattr(obj, "__bencode__"):
self.encode(obj.__bencode__())
elif hasattr(obj, "ite... | def encode(self, obj) | Add the given object to the result. | 2.669446 | 2.596726 | 1.028005 |
top = (200. / 3.) * c200**3.
bottom = np.log(1. + c200) - (c200 / (1. + c200))
return (top / bottom) | def calc_delta_c(c200) | Calculate characteristic overdensity from concentration.
Parameters
----------
c200 : ndarray or float
Cluster concentration parameter.
Returns
----------
ndarray or float
Cluster characteristic overdensity, of same type as c200. | 4.147305 | 4.367087 | 0.949673 |
print("\nCluster Ensemble:")
if notebook is True:
display(self._df)
elif notebook is False:
print(self._df)
self.massrich_parameters() | def show(self, notebook=notebook_display) | Display cluster properties and scaling relation parameters. | 12.470508 | 8.923075 | 1.397557 |
if offsets is None:
self._sigoffset = np.zeros(self.number) * units.Mpc
else:
self._sigoffset = utils.check_units_and_type(offsets, units.Mpc,
num=self.number)
self.rbins = utils.check_units_and_type(rbins... | def calc_nfw(self, rbins, offsets=None, numTh=200, numRoff=200,
numRinner=20, factorRouter=3) | Calculates Sigma and DeltaSigma profiles.
Generates the surface mass density (sigma_nfw attribute of parent
object) and differential surface mass density (deltasigma_nfw
attribute of parent object) profiles of each cluster, assuming a
spherical NFW model. Optionally includes the effect ... | 3.270936 | 2.976236 | 1.099018 |
assert value.shape[1]==1, 'Dimension mismatch'
self._N = value.shape[0]
self._Y = value | def Y(self,value) | set phenotype | 5.453571 | 6.032181 | 0.90408 |
assert value.shape[0]==self._N, 'Dimension mismatch'
self._K = value.shape[1]
self._F = value
self.clear_cache('predict','Yres') | def F(self,value) | set phenotype | 8.904984 | 9.714943 | 0.916628 |
assert value.shape[0]==self._K, 'Dimension mismatch'
assert value.shape[1]==1, 'Dimension mismatch'
self._B = value
self.clear_cache('predict','Yres') | def B(self,value) | set phenotype | 7.184046 | 7.78775 | 0.92248 |
result = []
atoms = allAtoms = molecule.atoms
visitedAtoms = {}
#
# Traverse all components of the graph to form
# the output string
while atoms:
atom = _get_lowest_symorder(atoms)
visitedAtoms[atom] = 1
visitedBonds = {}
nextTraverse = TraversalType()
... | def draw(molecule, TraversalType=SmilesTraversal) | (molecule)->canonical representation of a molecule
Well, it's only canonical if the atom symorders are
canonical, otherwise it's arbitrary.
atoms must have a symorder attribute
bonds must have a equiv_class attribute | 4.278445 | 4.319252 | 0.990552 |
'''Random graph generator. Does not generate self-edges.
out_degree : array-like of ints, controlling the out degree of each vertex.
'''
n = len(out_degree)
out_degree = np.asarray(out_degree, dtype=int)
if (out_degree >= n).any():
raise ValueError('Cannot have degree >= num_vertices')
row = np.repeat... | def random_graph(out_degree) | Random graph generator. Does not generate self-edges.
out_degree : array-like of ints, controlling the out degree of each vertex. | 3.327697 | 2.702093 | 1.231526 |
def delaunay_graph(X, weighted=False):
'''Delaunay triangulation graph.
'''
e1, e2 = _delaunay_edges(X)
pairs = np.column_stack((e1, e2))
w = paired_distances(X[e1], X[e2]) if weighted else None
return Graph.from_edge_pairs(pairs, num_vertices=X.shape[0], symmetric=True,
... | Delaunay triangulation graph. | null | null | null | |
def urquhart_graph(X, weighted=False):
'''Urquhart graph: made from the 2 shortest edges of each Delaunay triangle.
'''
e1, e2 = _delaunay_edges(X)
w = paired_distances(X[e1], X[e2])
mask = np.ones_like(w, dtype=bool)
bad_inds = w.reshape((-1, 3)).argmax(axis=1) + np.arange(0, len(e1), 3)
mask[bad_... | Urquhart graph: made from the 2 shortest edges of each Delaunay triangle. | null | null | null | |
if self._s is not None:
res = self._U.T.dot(b)
res /= self._s[:,np.newaxis]
res = self._U.dot(res)
elif self._chol is not None:
res = la.cho_solve((self._chol,self._lower),b=b,overwrite_b=overwrite_b,check_finite=check_finite)
else:
... | def solve(self,b,overwrite_b=False,check_finite=True) | solve A \ b | 3.029835 | 3.073451 | 0.985809 |
if p is None:
assert b.shape[:2]==(len(self.solver),self.dof_any)
solution = np.empty(b.shape)
#This is trivially parallelizable:
for p in range(self.P):
solution[p] = self.solver[p].solve(b=b[p])
return solution
else:
... | def solve(self,b,overwrite_b=False,check_finite=True, p=None) | solve A \ b | 4.584256 | 4.609047 | 0.994621 |
#assert b.shape[:2]==(len(self.solver),self.dof_any)
if self.schur_solver is None and self.A_any_solver is None:
assert ( (b is None) or (b.shape[0]==0) ) and ( (b_any is None) or (b_any.shape[0]==0) ), "shape missmatch"
return b, b_any
elif self.schur_... | def solve(self, b_any, b, check_finite=True, p=None) | solve A \ b | 2.469671 | 2.478933 | 0.996264 |
# First, try to resolve file: references to their contents
template_path = None
try:
is_file = template_text.startswith("file:")
except (AttributeError, TypeError):
pass # not a string
else:
if is_file:
template_path = template_text[5:]
if templat... | def preparse(template_text, lookup=None) | Do any special processing of a template, including recognizing the templating language
and resolving file: references, then return an appropriate wrapper object.
Currently Tempita and Python string interpolation are supported.
`lookup` is an optional callable that resolves any ambiguous templat... | 3.19409 | 2.985553 | 1.069849 |
with h5py.File(self.WORKING_DIRECTORY + '/' + self.output_file_name, 'w') as f:
header = f.create_group('header')
header.attrs['Title'] = 'Generated SNR Out'
header.attrs['Author'] = 'Generator by: Michael Katz'
header.attrs['Date/Time'] = str(datetime.d... | def hdf5_read_out(self) | Read out an hdf5 file.
Takes the output of :class:`gwsnrcalc.genconutils.genprocess.GenProcess`
and reads it out to an HDF5 file. | 3.213356 | 3.205513 | 1.002447 |
header = '#Generated SNR Out\n'
header += '#Generator by: Michael Katz\n'
header += '#Date/Time: {}\n'.format(datetime.datetime.now())
for which in ['x', 'y']:
header += '#' + which + 'val_name: {}\n'.format(getattr(self, which + 'val_name'))
header += ... | def txt_read_out(self) | Read out txt file.
Takes the output of :class:`gwsnrcalc.genconutils.genprocess.GenProcess`
and reads it out to a txt file. | 3.704125 | 3.697555 | 1.001777 |
installed = False
log('Checking if trigger function installed...', logger_name=_LOGGER_NAME)
try:
execute(connection, "SELECT pg_get_functiondef('public.psycopg2_pgevents_create_event'::regproc);")
installed = True
except ProgrammingError as e:
if e.args:
error... | def trigger_function_installed(connection: connection) | Test whether or not the psycopg2-pgevents trigger function is installed.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
Returns
-------
bool
True if the trigger function is installed, otherwise False. | 3.81261 | 3.694805 | 1.031884 |
installed = False
log('Checking if {}.{} trigger installed...'.format(schema, table), logger_name=_LOGGER_NAME)
statement = SELECT_TRIGGER_STATEMENT.format(
table=table,
schema=schema
)
result = execute(connection, statement)
if result:
installed = True
log('... | def trigger_installed(connection: connection, table: str, schema: str='public') | Test whether or not a psycopg2-pgevents trigger is installed for a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
Table whose trigger-existence will be checked.
schema: str
Schema to which the ta... | 3.825902 | 4.280148 | 0.893872 |
prior_install = False
if not overwrite:
prior_install = trigger_function_installed(connection)
if not prior_install:
log('Installing trigger function...', logger_name=_LOGGER_NAME)
execute(connection, INSTALL_TRIGGER_FUNCTION_STATEMENT)
else:
log('Trigger function... | def install_trigger_function(connection: connection, overwrite: bool=False) -> None | Install the psycopg2-pgevents trigger function against the database.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
overwrite: bool
Whether or not to overwrite existing installation of psycopg2-pgevents
trigger functi... | 4.333965 | 4.565368 | 0.949313 |
modifier = ''
if force:
modifier = 'CASCADE'
log('Uninstalling trigger function (cascade={})...'.format(force), logger_name=_LOGGER_NAME)
statement = UNINSTALL_TRIGGER_FUNCTION_STATEMENT.format(modifier=modifier)
execute(connection, statement) | def uninstall_trigger_function(connection: connection, force: bool=False) -> None | Uninstall the psycopg2-pgevents trigger function from the database.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
force: bool
If True, force the un-registration even if dependent triggers are still
installed. If Fals... | 6.381193 | 7.113817 | 0.897014 |
prior_install = False
if not overwrite:
prior_install = trigger_installed(connection, table, schema)
if not prior_install:
log('Installing {}.{} trigger...'.format(schema, table), logger_name=_LOGGER_NAME)
statement = INSTALL_TRIGGER_STATEMENT.format(
schema=schem... | def install_trigger(connection: connection, table: str, schema: str='public', overwrite: bool=False) -> None | Install a psycopg2-pgevents trigger against a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
Table for which the trigger should be installed.
schema: str
Schema to which the table belongs.
ov... | 3.378886 | 3.463808 | 0.975483 |
log('Uninstalling {}.{} trigger...'.format(schema, table), logger_name=_LOGGER_NAME)
statement = UNINSTALL_TRIGGER_STATEMENT.format(
schema=schema,
table=table
)
execute(connection, statement) | def uninstall_trigger(connection: connection, table: str, schema: str='public') -> None | Uninstall a psycopg2-pgevents trigger from a table.
Parameters
----------
connection: psycopg2.extensions.connection
Active connection to a PostGreSQL database.
table: str
Table for which the trigger should be uninstalled.
schema: str
Schema to which the table belongs.
... | 4.567657 | 5.037826 | 0.906672 |
site_url = getattr(settings, 'SITE_URL', False)
# If we don't define it explicitly
if not site_url:
protocol = settings.PROTOCOL
hostname = settings.DOMAIN
port = settings.PORT
if (protocol, port) in (('https://', 443), ('http://', 80)):
site_url = ''.join(m... | def absolutify(url) | Takes a URL and prepends the SITE_URL | 2.888149 | 2.748389 | 1.050852 |
def _config_loader(app, **kwargs_config):
InvenioConfigEntryPointModule(app=app)
if config:
InvenioConfigModule(app=app, module=config)
InvenioConfigInstanceFolder(app=app)
app.config.update(**kwargs_config)
InvenioConfigEnvironment(app=app, prefix='{0}_'.for... | def create_config_loader(config=None, env_prefix='APP') | Create a default configuration loader.
A configuration loader takes a Flask application and keyword arguments and
updates the Flask application's configuration as it sees fit.
This default configuration loader will load configuration in the following
order:
1. Load configuration from ``inveni... | 4.766053 | 4.172526 | 1.142247 |
def create_conf_loader(*args, **kwargs): # pragma: no cover
import warnings
warnings.warn(
'"create_conf_loader" has been renamed to "create_config_loader".',
DeprecationWarning
)
return create_config_loader(*args, **kwargs) | Create a default configuration loader.
.. deprecated:: 1.0.0b1
Use :func:`create_config_loader` instead. This function will be removed
in version 1.0.1. | null | null | null | |
token_type = auth_session.token_type
token = auth_session.oauth2credential.access_token
if not self._authorization_headers_valid(token_type, token):
message = 'Invalid token_type or token.'
raise LyftIllegalState(message)
headers = {
'Autho... | def _build_headers(self, method, auth_session) | Create headers for the request.
Parameters
method (str)
HTTP method (e.g. 'POST').
auth_session (Session)
The Session object containing OAuth 2.0 credentials.
Returns
headers (dict)
Dictionary of access headers to attach... | 5.147763 | 4.049453 | 1.271224 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.