code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''Estimate evals based on eval inclusion theorem + heuristic. :returns: Intervals object with inclusion intervals for eigenvalues ''' if len(indices) == 0: return utils.Intervals( [utils.Interval(mu-resnorm, mu+resnorm) for mu, resnorm in zi...
def _estimate_eval_intervals(ritz, indices, indices_remaining, eps_min=0, eps_max=0, eps_res=None)
Estimate evals based on eval inclusion theorem + heuristic. :returns: Intervals object with inclusion intervals for eigenvalues
3.338618
2.929047
1.139831
'''Correct the given approximate solution ``z`` with respect to the linear system ``linear_system`` and the deflation space defined by ``U``.''' c = self.linear_system.Ml*( self.linear_system.b - self.linear_system.A*z) c = utils.inner(self.W, c, ip_B=self.ip_B) ...
def correct(self, z)
Correct the given approximate solution ``z`` with respect to the linear system ``linear_system`` and the deflation space defined by ``U``.
5.406162
3.534467
1.529555
'''Result of preconditioned operator to deflation space, i.e., :math:`MM_lAM_rU`.''' if self._MAU is None: self._MAU = self.linear_system.M * self.AU return self._MAU
def MAU(self)
Result of preconditioned operator to deflation space, i.e., :math:`MM_lAM_rU`.
15.807408
3.269601
4.83466
'''Apply the projection and store inner product. :param v: the vector resulting from an application of :math:`M_lAM_r` to the current Arnoldi vector. (CG needs special treatment, here). ''' PAv, UAv = self.projection.apply_complement(Av, return_Ya=True) self.C = numpy....
def _apply_projection(self, Av)
Apply the projection and store inner product. :param v: the vector resulting from an application of :math:`M_lAM_r` to the current Arnoldi vector. (CG needs special treatment, here).
18.63711
4.039608
4.613594
'''Return the projected initial residual. Returns :math:`MPM_l(b-Ax_0)`. ''' if x0 is None: Mlr = self.linear_system.Mlb else: r = self.linear_system.b - self.linear_system.A*x0 Mlr = self.linear_system.Ml*r PMlr, self.UMlr = self.pro...
def _get_initial_residual(self, x0)
Return the projected initial residual. Returns :math:`MPM_l(b-Ax_0)`.
6.697779
4.244411
1.578023
r''':math:`\underline{B}=\langle V_{n+1},M_lAM_rU\rangle`. This property is obtained from :math:`C` if the operator is self-adjoint. Otherwise, the inner products have to be formed explicitly.''' (n_, n) = self.H.shape ls = self.linear_system if self._B_ is None ...
def B_(self)
r''':math:`\underline{B}=\langle V_{n+1},M_lAM_rU\rangle`. This property is obtained from :math:`C` if the operator is self-adjoint. Otherwise, the inner products have to be formed explicitly.
6.871138
3.212376
2.138958
'''Estimate time needed to run nsteps iterations with deflation Uses timings from :py:attr:`linear_system` if it is an instance of :py:class:`~krypy.linsys.TimedLinearSystem`. Otherwise, an :py:class:`~krypy.utils.OtherError` is raised. :param nsteps: number of iteratio...
def estimate_time(self, nsteps, ndefl, deflweight=1.0)
Estimate time needed to run nsteps iterations with deflation Uses timings from :py:attr:`linear_system` if it is an instance of :py:class:`~krypy.linsys.TimedLinearSystem`. Otherwise, an :py:class:`~krypy.utils.OtherError` is raised. :param nsteps: number of iterations. ...
5.070364
2.562236
1.978882
r'''Computes :math:`\langle C,M_lAM_rV_n\rangle` efficiently with a three-term recurrence.''' PAv, UAp = self.projection.apply_complement(Av, return_Ya=True) self._UAps.append(UAp) c = UAp.copy() rhos = self.rhos if self.iter > 0: c -= (1 + rhos[-1]/rh...
def _apply_projection(self, Av)
r'''Computes :math:`\langle C,M_lAM_rV_n\rangle` efficiently with a three-term recurrence.
6.259922
3.855958
1.623441
'''Compute Ritz vectors.''' H_ = self._deflated_solver.H (n_, n) = H_.shape coeffs = self.coeffs if indices is None else self.coeffs[:, indices] return numpy.c_[self._deflated_solver.V[:, :n], self._deflated_solver.projection.U].dot(coeffs)
def get_vectors(self, indices=None)
Compute Ritz vectors.
9.583748
8.424955
1.137543
'''Explicitly computes the Ritz residual.''' ritz_vecs = self.get_vectors(indices) return self._deflated_solver.linear_system.MlAMr * ritz_vecs \ - ritz_vecs * self.values
def get_explicit_residual(self, indices=None)
Explicitly computes the Ritz residual.
15.335743
12.181059
1.258983
'''Explicitly computes the Ritz residual norms.''' res = self.get_explicit_residual(indices) # apply preconditioner linear_system = self._deflated_solver.linear_system Mres = linear_system.M * res # compute norms resnorms = numpy.zeros(res.shape[1]) for ...
def get_explicit_resnorms(self, indices=None)
Explicitly computes the Ritz residual norms.
5.407186
4.703763
1.149545
try: from IPython.core.display import display, HTML except ImportError: print("IPython Notebook could not be loaded.") lib_js = ENV.get_template('ipynb_init_js.html') lib_css = ENV.get_template('ipynb_init_css.html') display(HTML(lib_js.render())) display(HTML(lib_css.rend...
def initialize_notebook()
Initialize the IPython notebook display elements
3.405974
3.337854
1.020408
'''Transform Pandas Timeseries into JSON format Parameters ---------- data: DataFrame or Series Pandas DataFrame or Series must have datetime index Returns ------- JSON to object.json_data Example ------- >>>vis.transform_dat...
def transform_data(self, data)
Transform Pandas Timeseries into JSON format Parameters ---------- data: DataFrame or Series Pandas DataFrame or Series must have datetime index Returns ------- JSON to object.json_data Example ------- >>>vis.transform_data(df) ...
3.360476
2.484885
1.352367
'''Build Rickshaw graph syntax with all data''' # Set palette colors if necessary if not self.colors: self.palette = self.env.get_template('palette.js') self.template_vars.update({'palette': self.palette.render()}) self.colors = {x['name']: 'palette.color()' ...
def _build_graph(self)
Build Rickshaw graph syntax with all data
4.44565
3.839993
1.157724
'''Save bearcart output to HTML and JSON. Parameters ---------- html_path: string, default 'index.html' Path for html output data_path: string, default 'data.json' Path for data JSON output js_path: string, default 'rickshaw.min.js' If...
def create_chart(self, html_path='index.html', data_path='data.json', js_path='rickshaw.min.js', css_path='rickshaw.min.css', html_prefix='')
Save bearcart output to HTML and JSON. Parameters ---------- html_path: string, default 'index.html' Path for html output data_path: string, default 'data.json' Path for data JSON output js_path: string, default 'rickshaw.min.js' If passed, th...
2.475994
1.457192
1.699154
self.chart_id = '_'.join(['bearcart', uuid4().hex]) self.template_vars.update({'chart_id': self.chart_id, 'y_axis_id': self.y_axis_id, 'legend_id': self.legend_id, 'slider_id': self.slider_i...
def _repr_html_(self)
Build the HTML representation for IPython.
4.570078
4.346051
1.051547
if type(y) is not int or type(mon) is not int or type(d) is not int or \ type(h) is not int or type(min_) is not int or type(s) is not int: raise KPError("Date variables must be integers") elif y > 9999 or y < 1 or mon > 12 or mon < 1 or d > 31 or d < 1 or \ ...
def set_expire(self, y = 2999, mon = 12, d = 28, h = 23, min_ = 59, s = 59)
This method is used to change the expire date of a group - y is the year between 1 and 9999 inclusive - mon is the month between 1 and 12 - d is a day in the given month - h is a hour between 0 and 23 - min_ is a minute between 0 and 59 - s is a s...
1.709797
1.710037
0.99986
return self.db.create_entry(self, title, image, url, username, password, comment, y, mon, d, h, min_, s)
def create_entry(self, title='', image=1, url='', username='', password='', comment='', y=2999, mon=12, d=28, h=23, min_=59, s=59)
This method creates an entry in this group. Compare to StdEntry for information about the arguments. One of the following arguments is needed: - title - url - username - password - comment
2.764663
3.105827
0.890154
if title is None or type(title) is not str: raise KPError("Need a new title.") else: self.title = title self.last_mod = datetime.now().replace(microsecond=0) return True
def set_title(self, title = None)
This method is used to change an entry title. A new title string is needed.
5.488715
4.776796
1.149037
if image is None or type(image) is not int: raise KPError("Need a new image number") else: self.image = image self.last_mod = datetime.now().replace(microsecond=0) return True
def set_image(self, image = None)
This method is used to set the image number. image must be an unsigned int.
6.048478
5.05156
1.197349
if url is None or type(url) is not str: raise KPError("Need a new image number") else: self.url = url self.last_mod = datetime.now().replace(microsecond=0) return True
def set_url(self, url = None)
This method is used to set the url. url must be a string.
7.42455
7.281053
1.019708
if username is None or type(username) is not str: raise KPError("Need a new image number") else: self.username = username self.last_mod = datetime.now().replace(microsecond=0) return True
def set_username(self, username = None)
This method is used to set the username. username must be a string.
6.693738
6.576587
1.017813
if password is None or type(password) is not str: raise KPError("Need a new image number") else: self.password = password self.last_mod = datetime.now().replace(microsecond=0) return True
def set_password(self, password = None)
This method is used to set the password. password must be a string.
6.75379
6.61979
1.020242
if comment is None or type(comment) is not str: raise KPError("Need a new image number") else: self.comment = comment self.last_mod = datetime.now().replace(microsecond=0) return True
def set_comment(self, comment = None)
This method is used to the the comment. comment must be a string.
6.790744
6.298379
1.078173
with open(self.filepath, 'rb') as handler: try: buf = handler.read() # There should be a header at least if len(buf) < 124: raise KPError('Unexpected file size. It should be more or' ...
def read_buf(self)
Read database file
6.188128
5.929348
1.043644
if self.filepath is not None: if path.isfile(self.filepath+'.lock'): remove(self.filepath+'.lock') self.filepath = None self.read_only = False self.lock() return True else: raise KPError('Can\'t clo...
def close(self)
This method closes the database correctly.
5.384486
5.088182
1.058234
self.password = None self.keyfile = None self.groups[:] = [] self.entries[:] = [] self._group_order[:] = [] self._entry_order[:] = [] self.root_group = v1Group() self._num_groups = 1 self._num_entries = 0 return True
def lock(self)
This method locks the database.
5.848776
5.405282
1.082048
if ((password is None or password == "") and (keyfile is None or keyfile == "")): raise KPError("A password/keyfile is needed") elif ((type(password) is not str and password is not None) or (type(keyfile) is not str and keyfile is not None)): ...
def unlock(self, password = None, keyfile = None, buf = None)
Unlock the database. masterkey is needed.
2.909564
2.837146
1.025525
if title is None: raise KPError("Need a group title to create a group.") elif type(title) is not str or image < 1 or(parent is not None and \ type(parent) is not v1Group) or type(image) is not int: raise KPError("Wrong type or value for title or imag...
def create_group(self, title = None, parent = None, image = 1, y = 2999, mon = 12, d = 28, h = 23, min_ = 59, s = 59)
This method creates a new group. A group title is needed or no group will be created. If a parent is given, the group will be created as a sub-group. title must be a string, image an unsigned int >0 and parent a v1Group. With y, mon, d, h, min_ and s you can set an expiration date li...
2.682417
2.530536
1.060019
if group is None: raise KPError("Need group to remove a group") elif type(group) is not v1Group: raise KPError("group must be v1Group") children = [] entries = [] if group in self.groups: # Save all children and entries to ...
def remove_group(self, group = None)
This method removes a group. The group needed to remove the group. group must be a v1Group.
3.906119
3.580024
1.091087
if group is None or type(group) is not v1Group: raise KPError("A valid group must be given.") elif parent is not None and type(parent) is not v1Group: raise KPError("parent must be a v1Group.") elif group is parent: raise KPError("group and parent mu...
def move_group(self, group = None, parent = None)
Append group to a new parent. group and parent must be v1Group-instances.
2.397298
2.256605
1.062347
if group is None or index is None: raise KPError("group and index must be set") elif type(group) is not v1Group or type(index) is not int: raise KPError("group must be a v1Group-instance and index " "must be an integer.") elif g...
def move_group_in_parent(self, group = None, index = None)
Move group to another position in group's parent. index must be a valid index of group.parent.groups
2.624547
2.497555
1.050847
for i in group.children: self.groups.remove(i) i.level = group.level + 1 self.groups.insert(self.groups.index(group) + 1, i) if i.children: self._move_group_helper(i)
def _move_group_helper(self, group)
A helper to move the chidren of a group.
3.007781
2.66745
1.127587
if (type(title) is not str or type(image) is not int or image < 0 or type(url) is not str or type(username) is not str or type(password) is not str or type(comment) is not str or type(y) is not int or type(mon)...
def create_entry(self, group = None, title = "", image = 1, url = "", username = "", password = "", comment = "", y = 2999, mon = 12, d = 28, h = 23, min_ = 59, s = 59)
This method creates a new entry. The group which should hold the entry is needed. image must be an unsigned int >0, group a v1Group. It is possible to give an expire date in the following way: - y is the year between 1 and 9999 inclusive - mon is the mo...
2.062794
1.961742
1.051512
if entry is None or type(entry) is not v1Entry: raise KPError("Need an entry.") elif entry in self.entries: entry.group.entries.remove(entry) self.entries.remove(entry) self._num_entries -= 1 return True else: ...
def remove_entry(self, entry = None)
This method can remove entries. The v1Entry-object entry is needed.
4.909809
3.824863
1.283656
if entry is None or group is None or type(entry) is not v1Entry or \ type(group) is not v1Group: raise KPError("Need an entry and a group.") elif entry not in self.entries: raise KPError("No entry found.") elif group in self.groups: entry...
def move_entry(self, entry = None, group = None)
Move an entry to another group. A v1Group group and a v1Entry entry are needed.
3.277663
2.775433
1.180956
if entry is None or index is None or type(entry) is not v1Entry \ or type(index) is not int: raise KPError("Need an entry and an index.") elif index < 0 or index > len(entry.group.entries)-1: raise KPError("Index is not valid.") elif entry not in sel...
def move_entry_in_group(self, entry = None, index = None)
Move entry to another position inside a group. An entry and a valid index to insert the entry in the entry list of the holding group is needed. 0 means that the entry is moved to the first position 1 to the second and so on.
2.330147
2.357278
0.988491
aes = AES.new(self._transf_randomseed, AES.MODE_ECB) # Encrypt the created hash for _ in range(self._key_transf_rounds): masterkey = aes.encrypt(masterkey) # Finally, hash it again... sha_obj = SHA256.new() sha_obj.update(masterkey) masterk...
def _transform_key(self, masterkey)
This method creates the key to decrypt the database
3.891467
3.961092
0.982423
sha = SHA256.new() sha.update(self.password.encode('utf-8')) return sha.digest()
def _get_passwordkey(self)
This method just hashes self.password.
4.014906
2.775684
1.446457
if not os.path.exists(self.keyfile): raise KPError('Keyfile not exists.') try: with open(self.keyfile, 'rb') as handler: handler.seek(0, os.SEEK_END) size = handler.tell() handler.seek(0, os.SEEK_SET) if s...
def _get_filekey(self)
This method creates a key from a keyfile.
2.239046
2.097158
1.067657
# Just decrypt the content with the created key aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) decrypted_content = aes.decrypt(crypted_content) padding = decrypted_content[-1] if sys.version > '3': padding = decrypted_content[-1] else: ...
def _cbc_decrypt(self, final_key, crypted_content)
This method decrypts the database
2.730364
2.869021
0.951671
aes = AES.new(final_key, AES.MODE_CBC, self._enc_iv) padding = (16 - len(content) % AES.block_size) for _ in range(padding): content += chr(padding).encode() temp = bytes(content) return aes.encrypt(temp)
def _cbc_encrypt(self, content, final_key)
This method encrypts the content.
3.607184
3.608734
0.999571
if field_type == 0x0000: # Ignored (commentar block) pass elif field_type == 0x0001: group.id_ = struct.unpack('<I', decrypted_content[:4])[0] elif field_type == 0x0002: try: group.title = struct.unpack('<{0}s'.format(fiel...
def _read_group_field(self, group, levels, field_type, field_size, decrypted_content)
This method handles the different fields of a group
1.794591
1.791463
1.001746
if field_type == 0x0000: # Ignored pass elif field_type == 0x0001: entry.uuid = decrypted_content[:16] elif field_type == 0x0002: entry.group_id = struct.unpack('<I', decrypted_content[:4])[0] elif field_type == 0x0003: ...
def _read_entry_field(self, entry, field_type, field_size, decrypted_content)
This method handles the different fields of an entry
1.444275
1.440211
1.002822
# Just copied from original KeePassX source date_field = struct.unpack('<5B', decrypted_content[:5]) dw1 = date_field[0] dw2 = date_field[1] dw3 = date_field[2] dw4 = date_field[3] dw5 = date_field[4] y = (dw1 << 6) | (dw2 >> 2) ...
def _get_date(self, decrypted_content)
This method is used to decode the packed dates of entries
2.261991
2.195961
1.030069
# Just copied from original KeePassX source y, mon, d, h, min_, s = date.timetuple()[:6] dw1 = 0x0000FFFF & ((y>>6) & 0x0000003F) dw2 = 0x0000FFFF & ((y & 0x0000003F)<<2 | ((mon>>2) & 0x00000003)) dw3 = 0x0000FFFF & (((mon & 0x0000003)<<6) | ((d & 0x0000001F)<<...
def _pack_date(self, date)
This method is used to encode dates
2.21204
2.161787
1.023246
if levels[0] != 0: raise KPError("Invalid group tree") for i in range(len(self.groups)): if(levels[i] == 0): self.groups[i].parent = self.root_group self.groups[i].index = len(self.root_group.children) self.root_g...
def _create_group_tree(self, levels)
This method creates a group tree
2.472254
2.454556
1.00721
if field_type == 0x0000: # Ignored (commentar block) pass elif field_type == 0x0001: if group.id_ is not None: return (4, struct.pack('<I', group.id_)) elif field_type == 0x0002: if group.title is not None: ...
def _save_group_field(self, field_type, group)
This method packs a group field
1.845686
1.825593
1.011006
if field_type == 0x0000: # Ignored pass elif field_type == 0x0001: if entry.uuid is not None: return (16, entry.uuid) elif field_type == 0x0002: if entry.group_id is not None: return (4, struct.pack('<I', e...
def _save_entry_field(self, field_type, entry)
This group packs a entry field
1.535276
1.524422
1.00712
# keyword-only arguments, vars and fallback are directly passed through raw = kwargs.get('raw', False) value = self.get(section, option, **kwargs) if raw: return value return self.custodia_client.get_secret(value)
def getsecret(self, section, option, **kwargs)
Get a secret from Custodia
8.077936
6.38743
1.264661
group = 'custodia.{}'.format(menu) eps = list(pkg_resources.iter_entry_points(group, name)) if len(eps) > 1: raise ValueError( "Multiple entry points for {} {}: {}".format(menu, name, eps)) elif len(eps) == 1: # backwards compatibility with old setuptools ep = ep...
def _load_plugin_class(menu, name)
Load Custodia plugin Entry points are preferred over dotted import path.
3.492404
3.021344
1.155911
# set umask before any plugin gets a chance to create a file os.umask(config['umask']) for s in cfgparser.sections(): if s in {'ENV', 'global'}: # ENV section is only used for interpolation continue if s.startswith('/'): menu = 'consumers' ...
def _load_plugins(config, cfgparser)
Load and initialize plugins
3.682214
3.642055
1.011026
name = po.name typ = po.typ default = po.default handler = getattr(self, '_get_{}'.format(typ), None) if handler is None: raise ValueError(typ) self.seen.add(name) # pylint: disable=not-callable if not self.parser.has_option(self.sec...
def get(self, po)
Lookup value for a PluginOption instance Args: po: PluginOption Returns: converted value
5.84109
6.037467
0.967474
# On requests we imply 'simple' if there is no input message if msg is None: return if not isinstance(msg, string_types): raise InvalidMessage("The 'value' attribute is not a string") self.name = name self.payload = msg self.msg_type = ...
def parse(self, msg, name)
Parses a simple message :param msg: the json-decoded value :param name: the requested name :raises UnknownMessageType: if the type is not 'simple' :raises InvalidMessage: if the message cannot be parsed or validated
8.042185
6.533685
1.23088
if arg.startswith(('http://', 'https://', 'http+unix://')): return arg if arg.startswith('./'): arg = os.path.abspath(arg) elif not arg.startswith('/'): raise argparse.ArgumentTypeError( 'Unix socket path must start with / or ./') # assume it is a unix socket ...
def server_check(arg)
Check and format --server arg
3.92274
3.78916
1.035253
prefix, realm = name.split(u'@') if u'/' in prefix: service, host = prefix.rsplit(u'/', 1) return service, host, realm else: return None, prefix, realm
def krb5_unparse_principal_name(name)
Split a Kerberos principal name into parts Returns: * ('host', hostname, realm) for a host principal * (servicename, hostname, realm) for a service principal * (None, username, realm) for a user principal :param text name: Kerberos principal name :return: (service, host, realm) or (No...
3.487944
2.928111
1.191192
def exception(self, msg, *args, **kwargs): extra = kwargs.setdefault('extra', {}) extra['exc_fullstack'] = self.isEnabledFor(logging.DEBUG) kwargs['exc_info'] = True self.log(logging.ERROR, msg, *args, **kwargs) logger = logging.getLogger(name) logger.exception = six.cr...
def getLogger(name)
Create logger with custom exception() method
3.220446
3.140479
1.025463
extra = kwargs.setdefault('extra', {}) extra['exc_fullstack'] = self.isEnabledFor(logging.DEBUG) kwargs['exc_info'] = True self.log(logging.ERROR, msg, *args, **kwargs)
def exception(self, msg, *args, **kwargs)
Like standard exception() logger but only print stack in debug mode
4.065864
3.415198
1.190521
try: jtok = JWT(jwt=msg) except Exception as e: raise InvalidMessage('Failed to parse message: %s' % str(e)) try: token = jtok.token if isinstance(token, JWE): token.decrypt(self.kkstore.server_keys[KEY_USAGE_ENC]) ...
def parse(self, msg, name)
Parses the message. We check that the message is properly formatted. :param msg: a json-encoded value containing a JWS or JWE+JWS token :raises InvalidMessage: if the message cannot be parsed or validated :returns: A verified payload
4.248221
4.081309
1.040897
invalid = ':/@' if set(string).intersection(invalid): msg = 'Invalid instance name {}'.format(string) raise argparse.ArgumentTypeError(msg) return string
def instance_name(string)
Check for valid instance name
5.794764
5.062906
1.144553
path_chain = request['path_chain'] if not path_chain or path_chain[0] != '': # no path or not an absolute path raise HTTPError(400) # auth framework here authers = config.get('authenticators') if authers is None: raise HTTPError(403) ...
def pipeline(self, config, request)
The pipeline() function handles authentication and invocation of the correct consumer based on the server configuration, that is provided at initialization time. When authentication is performed all the authenticators are executed. If any returns False, authentication fails and a 403 ...
3.052684
2.903981
1.051206
data = self._init_data(params) response = requests.post(REQUESTS_URL, headers={ 'Authorization': self.auth.authorize('POST', REQUESTS_URL, params), 'User-Agent': USER_AGENT, }, data=data, files={'image_request[image]': (filename, image)}) return self._unw...
def image_request(self, image, filename, params=None)
Send an image for classification. The image is a file-like object. The params parameter is optional. On success this method will immediately return a job information. Its status will initially be :py:data:`cloudsight.STATUS_NOT_COMPLETED` as it usually takes 6-12 seconds for the...
4.784506
5.385595
0.888389
data = self._init_data(params) data['image_request[remote_image_url]'] = image_url response = requests.post(REQUESTS_URL, headers={ 'Authorization': self.auth.authorize('POST', REQUESTS_URL, data), 'User-Agent': USER_AGENT, }, data=data) return se...
def remote_image_request(self, image_url, params=None)
Send an image for classification. The imagewill be retrieved from the URL specified. The params parameter is optional. On success this method will immediately return a job information. Its status will initially be :py:data:`cloudsight.STATUS_NOT_COMPLETED` as it usually takes 6-...
4.330841
4.927075
0.878988
url = RESPONSES_URL + token response = requests.get(url, headers={ 'Authorization': self.auth.authorize('GET', url), 'User-Agent': USER_AGENT, }) return self._unwrap_error(response)
def image_response(self, token)
Contact the server and update the job status. After a request has been submitted, it usually takes 6-12 seconds to receive a completed response. We recommend polling for a response every 1 second after a 4 second delay from the initial request, while the status is :py:data:`clou...
5.172263
6.330016
0.817101
url = '%s/%s/repost' % (REQUESTS_URL, token) response = requests.post(url, headers={ 'Authorization': self.auth.authorize('POST', url), 'User-Agent': USER_AGENT, }) if response.status_code == 200: return return self._unwrap_error(res...
def repost(self, token)
Repost the job if it has timed out (:py:data:`cloudsight.STATUS_TIMEOUT`). :param token: Job token as returned from :py:meth:`cloudsight.API.image_request` or :py:meth:`cloudsight.API.remote_image_request`
3.820815
4.407791
0.866832
delta = datetime.timedelta(seconds=timeout) timeout_at = datetime.datetime.now() + delta time.sleep(min(timeout, INITIAL_POLL_WAIT)) response = self.image_response(token) while response['status'] == STATUS_NOT_COMPLETED \ and datetime.datetime.now() < time...
def wait(self, token, timeout=DEFAULT_POLL_TIMEOUT)
Wait for the job until it has been processed. This method will block for up to `timeout` seconds. This method will wait for 4 seconds after the initial request and then will call :py:meth:`cloudsight.API.image_response` method every second until the status changes. :par...
3.70295
3.326757
1.113081
(version, timestamp, magic_int, co, is_pypy, source_size) = load_module(input_pyc) assert version == float(src_version), ( "Need Python %s bytecode; got bytecode for version %s" % (src_version, version)) magic_int = magic2int(magics[dest_version]) write_bytecode_file(output_pyc...
def copy_magic_into_pyc(input_pyc, output_pyc, src_version, dest_version)
Bytecodes are the same except the magic number, so just change that
5.53182
5.748203
0.962356
if inst.opname in ('JUMP_IF_FALSE', 'JUMP_IF_TRUE'): i += 1 assert i < n assert instructions[i].opname == 'POP_TOP' new_inst.offset = offset new_inst.opname = ( 'POP_JUMP_IF_FALSE' if inst.opname == 'JUMP_IF_FALSE' else 'POP_JUMP_IF_TRUE' ) ne...
def transform_26_27(inst, new_inst, i, n, offset, instructions, new_asm)
Change JUMP_IF_FALSE and JUMP_IF_TRUE to POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE
3.899018
3.734629
1.044018
add_size = xdis.op_size(new_inst.opcode, opcode_33) if inst.opname in ('MAKE_FUNCTION','MAKE_CLOSURE'): # Previous instruction should be a load const which # contains the name of the function to call prev_inst = instructions[i-1] assert prev_inst.opname == 'LOAD_CONST' ...
def transform_32_33(inst, new_inst, i, n, offset, instructions, new_asm)
MAKEFUNCTION adds another const. probably MAKECLASS as well
2.844187
2.82198
1.007869
add_size = xdis.op_size(new_inst.opcode, opcode_33) if inst.opname in ('MAKE_FUNCTION','MAKE_CLOSURE'): # Previous instruction should be a load const which # contains the name of the function to call prev_inst = instructions[i-1] assert prev_inst.opname == 'LOAD_CONST' ...
def transform_33_32(inst, new_inst, i, n, offset, instructions, new_asm)
MAKE_FUNCTION, and MAKE_CLOSURE have an additional LOAD_CONST of a name that are not in Python 3.2. Remove these.
3.422954
3.263803
1.048762
shortname = osp.basename(input_pyc) if shortname.endswith('.pyc'): shortname = shortname[:-4] src_version = conversion_to_version(conversion_type, is_dest=False) dest_version = conversion_to_version(conversion_type, is_dest=True) if output_pyc is None: output_pyc = "%s-%s.pyc" ...
def main(conversion_type, input_pyc, output_pyc)
Convert Python bytecode from one version to another. INPUT_PYC contains the input bytecode path name OUTPUT_PYC contians the output bytecode path name if supplied The --conversion type option specifies what conversion to do. Note: there are a very limited set of conversions currently supported. H...
3.836238
3.895107
0.984886
self.prepare_storage() self.str = self.load_file(fpath) if fpath else self.sanitize(str) self.validate_config() self.generate_kgrams() self.hash_kgrams() self.generate_fingerprints() return self.fingerprints
def generate(self, str=None, fpath=None)
generates fingerprints of the input. Either provide `str` to compute fingerprint directly from your string or `fpath` to compute fingerprint from the text of the file. Make sure to have your text decoded in `utf-8` format if you pass the input string. Args: str (Optional(str)): string whose fingerp...
5.763339
5.576248
1.033551
if os.stat(asm_path).st_size == 0: print("Size of assembly file %s is zero" % asm_path) sys.exit(1) asm = asm_file(asm_path) if not pyc_file and asm_path.endswith('.pyasm'): pyc_file = asm_path[:-len('.pyasm')] + '.pyc' write_pycfile(pyc_file, asm)
def main(pyc_file, asm_path)
Create Python bytecode from a Python assembly file. ASM_PATH gives the input Python assembly file. We suggest ending the file in .pyc If --pyc-file is given, that indicates the path to write the Python bytecode. The path should end in '.pyc'. See https://github.com/rocky/python-xasm/blob/master/H...
2.872262
3.027004
0.94888
to_hash = req.body if type(req.body) is bytes else req.body.encode('utf-8') if req.method in ('POST', 'PUT'): return { 'hash': hashlib.sha256(to_hash).hexdigest(), 'alg': 'sha256', }
def payload_body(req)
A generator that will include the sha256 signature of the request's body in the JWT payload. This is only done if the request could have a body: if the method is POST or PUT. >>> auth = JWTAuth('secret') >>> auth.add_field('body', payload_body)
3.160464
3.60744
0.876096
self.add_field('exp', lambda req: int(time.time() + secs))
def expire(self, secs)
Adds the standard 'exp' field, used to prevent replay attacks. Adds the 'exp' field to the payload. When a request is made, the field says that it should expire at now + `secs` seconds. Of course, this provides no protection unless the server reads and interprets this field.
11.995678
7.547697
1.589316
payload = {} for field, gen in self._generators.items(): value = None if callable(gen): value = gen(request) else: value = gen if value: payload[field] = value return payload
def _generate(self, request)
Generate a payload for the given request.
3.321252
2.799647
1.186311
tt = toctree divider = '<li class="divider"></li>' if divider else '' # Append anything just before the closing </ul>. if appendix: tt = re.sub(r'(</ul>$)', r'{}\1'.format(appendix), tt) # Add class attribute to all <ul> elements. tt = re.sub(r'<ul>', r'<ul class="">'...
def tt2nav(toctree, klass=None, appendix=None, divider=False)
Injects ``has-dropdown`` and ``dropdown`` classes to HTML generated by the :func:`toctree` function. :param str toctree: HTML generated by the :func:`toctree` function.
4.347679
4.156355
1.046032
if path.isfile(script_path): input = ( % script_path + ) cmd = "env -i bash".split() p = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=PIPE) stdout_data, stderr_data = p.communicate(input=input) if stderr_data: raise ShellScriptException(script...
def list_vars(script_path, ignore=IGNORE_DEFAULT)
Given a shell script, returns a list of shell variable names. Note: this method executes the script, so beware if it contains side-effects. :param script_path: Path the a shell script :type script_path: str or unicode :param ignore: variable names to ignore. By default we ignore variables ...
4.65489
4.573666
1.017759
# Iterate over every var independently: # This is slower than using env, but enables us to capture multiline variables return dict((var, get_var(script_path, var)) for var in list_vars(script_path))
def get_vars(script_path, ignore=IGNORE_DEFAULT)
Gets the values of environment variables defined in a shell script. Note: this method executes the script potentially many times. :param script_path: Path the a shell script :type script_path: str or unicode :param ignore: variable names to ignore. By default we ignore variables tha...
11.436397
11.910182
0.96022
if path.isfile(script_path): input = '. "%s"; echo -n "$%s"\n'% (script_path, var) pipe = Popen(["bash"], stdout=PIPE, stdin=PIPE, stderr=PIPE) stdout_data, stderr_data = pipe.communicate(input=input) if stderr_data: raise ShellScriptException(script_path, stderr_da...
def get_var(script_path, var)
Given a script, and the name of an environment variable, returns the value of the environment variable. :param script_path: Path the a shell script :type script_path: str or unicode :param var: environment variable name :type var: str or unicode :return: str
4.077342
4.119606
0.989741
def get_current_price(fsyms, tsyms, e='all', try_conversion=True, full=False, format='raw'): # select API function based on 'full' parameter value if not full: func = 'pricemulti' else: func = 'pricemultifull' # convert single fsym and tsym input to single element lists if ...
Get latest trading price or full trading information in display or raw format for the specified FROM/TO currency pairs. Args: fsyms: Single string or list of FROM symbols. tsyms: Single string or list of TO symbols. e: Default returns average price across all exchanges. Can be set to the name of a s...
null
null
null
def get_current_trading_info(fsym, tsym, markets='all', try_conversion=True, format='raw'): # load data url = build_url('generateAvg', fsym=fsym, tsym=tsym, markets=markets, try_conversion=try_conversion) data = load_data(url) # select format to return if...
Get the latest trading info of the requested pair as a volume weighted average based on the markets requested. Args: fsym: FROM symbol. tsym: TO symbol. markets: List containing the market names. try_conversion: If the crypto does not trade directly into the toSymbol requested, BTC will be used...
null
null
null
def get_day_average_price(fsym, tsym, e='all', try_conversion=True, avg_type='HourVWAP', utc_hour_diff=0): # load data url = build_url('dayAvg', fsym=fsym, tsym=tsym, e=e, try_conversion=try_conversion, avg_type=avg_type, utc_hour_diff=utc_hour_dif...
Get the current days average price of a currency pair. Args: fsym: FROM symbol. tsym: TO symbol. e: Default returns average price across all exchanges. Can be set to the name of a single exchange. try_conversion: If the crypto does not trade directly into the toSymbol requested, BTC will be use...
null
null
null
def get_historical_eod_price(fsym, tsyms, date, e='all', try_conversion=True): # convert single fsym and tsym input to single element lists if not isinstance(tsyms, list): tsyms = [tsyms] # convert date to timestamp ts = date_to_timestamp(date) # load data url = build_url("pricehistorical", fsym...
Get end of day price for cryptocurrency in any other currency for the requested timestamp. Args: fsym: FROM symbol. tsyms: Single string or list of TO symbols. date: Date as string with this format: "Y-m-d H-M-S". e: Default returns average price across all exchanges. Can be set to the name of a ...
null
null
null
def get_historical_data(fsym, tsym, freq, info='full', e='all', try_conversion=True, aggregate=1, limit=1440, to_ts=False): # load data url = build_url(freq, fsym=fsym, tsym=tsym, freq=freq, e=e, try_conversion=try_conversion, aggregate=agg...
Get minute-by-minute historical price and volume information for the requested currency pair. Available data is limited to the last 7 days. Args: fsym: FROM symbol. tsym: TO symbol. freq: Frequency of the data. Can be set to 'minute', 'hour' or 'day'. info: Select price or volume information to retu...
null
null
null
uri, extension = posixpath.splitext(url) return safe64.dir(uri) + extension
def url2fs(url)
encode a URL to be safe as a filename
16.802708
14.962294
1.123003
# the first response... slot = [0] * len(slots) for i in range(reduce(operator.mul, slots)): yield slot carry = 1 # iterate from the least to the most significant digit for j in range(len(slots), 0, -1): k = j - 1 ...
def xindexes(slots)
Generate list of possible indexes into a list of slots. Best way to think of this is as a number where each digit might have a different radix. E.g.: (10, 10, 10) would return 10 x 10 x 10 = 1000 responses from (0, 0, 0) to (9, 9, 9), (2, 2, 2, 2) would return 2 x 2 x 2 x 2 = 16 responses f...
4.162471
3.814204
1.091308
if srs.lower() == '+init=epsg:900913': return True # observed srs = dict([p.split('=') for p in srs.split() if '=' in p]) # expected # note, common optional modifiers like +no_defs, +over, and +wkt # are not pairs and should not prevent matching gym = '+proj=merc +a=637813...
def is_merc_projection(srs)
Return true if the map projection matches that used by VEarth, Google, OSM, etc. Is currently necessary for zoom-level shorthand for scale-denominator.
3.485868
3.569503
0.976569
styles = [] # # First, look at all the stylesheets defined in the map itself. # for stylesheet in map_el.findall('Stylesheet'): map_el.remove(stylesheet) content, mss_href = fetch_embedded_or_remote_src(stylesheet, dirs) if content: styles.appe...
def extract_declarations(map_el, dirs, scale=1, user_styles=[])
Given a Map element and directories object, remove and return a complete list of style declarations from any Stylesheet elements found within.
5.719779
5.781096
0.989394
ds = sources.DataSources(dirs.source, local_conf) # build up the configuration for spec in map_el.findall('DataSourcesConfig'): map_el.remove(spec) src_text, local_base = fetch_embedded_or_remote_src(spec, dirs) if not src_text: continue ds.add_c...
def expand_source_declarations(map_el, dirs, local_conf)
This provides mechanism for externalizing and sharing data sources. The datasource configs are python files, and layers reference sections within that config: <DataSourcesConfig src="datasources.cfg" /> <Layer class="road major" source_name="planet_osm_major_roads" /> <Layer class="road minor" sou...
3.589646
3.297002
1.088761
scale_tests = [test for test in filter.tests if test.isMapScaled()] other_tests = [test for test in filter.tests if not test.isMapScaled()] # these will be replaced with values as necessary minscale, maxscale, filter = None, None, None for scale_test in scale_tests: if scale_...
def make_rule(filter, *symbolizers)
Given a Filter and some symbolizers, return a Rule prepopulated with applicable min/max scale denominator and filter.
2.859858
2.757754
1.037024
for test in selector.allTests(): if not test.isCompatible(filter.tests): return False return True
def is_applicable_selector(selector, filter)
Given a Selector and Filter, return True if the Selector is compatible with the given Filter, and False if they contradict.
10.081089
8.458993
1.19176
property_map = {'polygon-fill': 'fill', 'polygon-opacity': 'fill-opacity', 'polygon-gamma': 'gamma', 'polygon-meta-output': 'meta-output', 'polygon-meta-writer': 'meta-writer'} property_names = property_map.keys() # a place to put rules rules = [] ...
def get_polygon_rules(declarations)
Given a Map element, a Layer element, and a list of declarations, create a new Style element with a PolygonSymbolizer, add it to Map and refer to it in Layer.
3.54803
3.62709
0.978203
property_map = {'raster-opacity': 'opacity', 'raster-mode': 'mode', 'raster-scaling': 'scaling' } property_names = property_map.keys() # a place to put rules rules = [] for (filter, values) in filtered_property_declarations(declarat...
def get_raster_rules(declarations)
Given a Map element, a Layer element, and a list of declarations, create a new Style element with a RasterSymbolizer, add it to Map and refer to it in Layer. The RasterSymbolizer will always created, even if there are no applicable declarations.
5.326285
4.976239
1.070344
property_map = {'line-color': 'stroke', 'line-width': 'stroke-width', 'line-opacity': 'stroke-opacity', 'line-join': 'stroke-linejoin', 'line-cap': 'stroke-linecap', 'line-dasharray': 'stroke-dasharray', 'line-meta-output': 'meta-output', 'line-meta-w...
def get_line_rules(declarations)
Given a list of declarations, return a list of output.Rule objects. This function is wise to line-<foo>, inline-<foo>, and outline-<foo> properties, and will generate multiple LineSymbolizers if necessary.
1.850411
1.764773
1.048526
scheme, host, remote_path, params, query, fragment = urlparse(href) assert scheme in ('http','https'), 'Scheme must be either http or https, not "%s" (for %s)' % (scheme,href) head, ext = posixpath.splitext(posixpath.basename(remote_path)) head = sub(r'[^\w\-_]', '', head) hash = md5(href...
def locally_cache_remote_file(href, dir)
Locally cache a remote resource using a predictable file name and awareness of modification date. Assume that files are "normal" which is to say they have filenames with extensions.
2.713227
2.752526
0.985723
# support latest mapnik features of auto-detection # of image sizes and jpeg reading support... # http://trac.mapnik.org/ticket/508 mapnik_auto_image_support = (MAPNIK_VERSION >= 701) mapnik_requires_absolute_paths = (MAPNIK_VERSION < 601) file_href = urljoin(dirs.source.rstrip('/')+'/', f...
def post_process_symbolizer_image_file(file_href, dirs)
Given an image file href and a set of directories, modify the image file name so it's correct with respect to the output and cache directories.
5.696013
5.822587
0.978262
property_map = {'shield-face-name': 'face_name', 'shield-fontset': 'fontset', 'shield-size': 'size', 'shield-fill': 'fill', 'shield-character-spacing': 'character_spacing', 'shield-line-spacing': 'line_spacing', ...
def get_shield_rule_groups(declarations, dirs)
Given a list of declarations, return a list of output.Rule objects. Optionally provide an output directory for local copies of image files.
2.595074
2.583154
1.004615
property_map = {'point-file': 'file', 'point-width': 'width', 'point-height': 'height', 'point-type': 'type', 'point-allow-overlap': 'allow_overlap', 'point-meta-output': 'meta-output', 'point-meta-writer': 'meta-writer'} property_names = pro...
def get_point_rules(declarations, dirs)
Given a list of declarations, return a list of output.Rule objects. Optionally provide an output directory for local copies of image files.
2.93
2.839968
1.031701
property_map = {'polygon-pattern-file': 'file', 'polygon-pattern-width': 'width', 'polygon-pattern-height': 'height', 'polygon-pattern-type': 'type', 'polygon-meta-output': 'meta-output', 'polygon-meta-writer': 'meta-writer'} property_names = property_map.keys(...
def get_polygon_pattern_rules(declarations, dirs)
Given a list of declarations, return a list of output.Rule objects. Optionally provide an output directory for local copies of image files.
2.96065
2.857937
1.035939