code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
url = '{}/block/info/{}'.format(self._url, block) return self.make_request(url)
def get_block_info(self, block)
Args: block: block number (eg: 223212) block hash (eg: 0000000000000000210b10d620600dc1cc2380bb58eb2408f9767eb792ed31fa) word "last" - this will always return the latest block word "first" - this will always return the first block Returns: ...
5.381276
6.321226
0.851303
for access_role in roles.keys(): setattr(cls, "is_" + access_role, lambda x: False)
def generate_is_role_functions(cls, roles)
Generate `class.is_{role}()` methods for a class. :param class cls: The python class to be modified. :param dict roles: The roles to use for generation. This method is intended to be used by an inheriting class to generate `is_{role}()` methods based on the roles provided durin...
6.963854
5.351528
1.301283
from .models import PIDStatus # Allow empty status if value is None: return None if not hasattr(PIDStatus, value): raise click.BadParameter('Status needs to be one of {0}.'.format( ', '.join([s.name for s in PIDStatus]) )) return getattr(PIDStatus, value)
def process_status(ctx, param, value)
Return status value.
3.825262
3.576921
1.069429
from .models import PersistentIdentifier if bool(object_type) ^ bool(object_uuid): raise click.BadParameter('Speficy both or any of --type and --uuid.') new_pid = PersistentIdentifier.create( pid_type, pid_value, status=status, object_type=object_type, ...
def create(pid_type, pid_value, status, object_type, object_uuid)
Create new persistent identifier.
3.141723
2.953271
1.063811
from .models import PersistentIdentifier obj = PersistentIdentifier.get(pid_type, pid_value) if status is not None: obj.status = status obj.assign(object_type, object_uuid, overwrite=overwrite) db.session.commit() click.echo(obj.status)
def assign(pid_type, pid_value, status, object_type, object_uuid, overwrite)
Assign persistent identifier.
3.198567
2.94578
1.085813
from .models import PersistentIdentifier obj = PersistentIdentifier.get(pid_type, pid_value) obj.unassign() db.session.commit() click.echo(obj.status)
def unassign(pid_type, pid_value)
Unassign persistent identifier.
4.5572
3.833974
1.188636
from .models import PersistentIdentifier obj = PersistentIdentifier.get(pid_type, pid_value) if obj.has_object(): click.echo('{0.object_type} {0.object_uuid} {0.status}'.format(obj))
def get_object(pid_type, pid_value)
Get an object behind persistent identifier.
4.080602
3.617344
1.128066
from .models import PersistentIdentifier pids = PersistentIdentifier.query.filter_by( object_type=object_type, object_uuid=object_uuid ) if status: pids = pids.filter_by(status=status) for found_pid in pids.all(): click.echo( '{0.pid_type} {0.pid_value} {0....
def dereference_object(object_type, object_uuid, status)
Show linked persistent identifier(s).
2.89053
2.412025
1.198383
def process_item(item): m = _LIST_RE.match(item) if m: contents = m.group(1) if not contents: item = [] else: item = process_m2m(contents) else: if item == 'TRUE': item = True eli...
def Deserializer(stream_or_string, **options)
Deserialize a stream or string of CSV data.
3.251849
3.28286
0.990554
pid_field = current_app.config['PIDSTORE_RECID_FIELD'] assert pid_field not in data provider = RecordIdProvider.create( object_type='rec', object_uuid=record_uuid) data[pid_field] = provider.pid.pid_value return provider.pid
def recid_minter(record_uuid, data)
Mint record identifiers. This is a minter specific for records. With the help of :class:`invenio_pidstore.providers.recordid.RecordIdProvider`, it creates the PID instance with `rec` as predefined `object_type`. Procedure followed: (we will use `control_number` as value of `PIDSTORE_RECID_FIEL...
3.741379
3.084292
1.213043
endpoint = current_app.config['PIDSTORE_OBJECT_ENDPOINTS'].get( m.object_type) if endpoint and m.object_uuid: return Markup('<a href="{0}">{1}</a>'.format( url_for(endpoint, id=m.object_uuid), _('View'))) return ''
def object_formatter(v, c, m, p)
Format object view link.
4.129201
3.787653
1.090174
self._service.push_tx(tx) return bitcoin.txhash(tx)
def push(self, tx)
Args: tx: hex of signed transaction Returns: pushed transaction
17.973537
25.078468
0.716692
if len(hash) < 64: txs = self._service.list_transactions(hash, account=account, max_transactions=max_transactions) unspents = self._service.list_unspents(hash, min_confirmations=min_confirmations) return {'transactions': txs, 'unspents': unspents} else: ...
def get(self, hash, account="*", max_transactions=100, min_confirmations=6, raw=False)
Args: hash: can be a bitcoin address or a transaction id. If it's a bitcoin address it will return a list of transactions up to ``max_transactions`` a list of unspents with confirmed transactions greater or equal to ``min_confirmantions`` account (...
2.418428
2.639781
0.916147
to = [to] if not isinstance(to, list) else to amount = sum([amount for addr, amount in to]) n_outputs = len(to) + 1 # change if op_return: n_outputs += 1 # select inputs inputs, change = self._select_inputs(from_address, amount, n_outputs, min_co...
def simple_transaction(self, from_address, to, op_return=None, min_confirmations=6)
Args: from_address (str): bitcoin address originating the transaction to: tuple of ``(to_address, amount)`` or list of tuples ``[(to_addr1, amount1), (to_addr2, amount2)]``. Amounts are in *satoshi* op_return (str): ability to set custom ``op_return`` min_confirmations (i...
2.773262
2.939392
0.943481
# prepare inputs and outputs for bitcoin inputs = [{'output': '{}:{}'.format(input['txid'], input['vout']), 'value': input['amount']} for input in inputs] tx = bitcoin.mktx(inputs, outputs) return tx
def build_transaction(self, inputs, outputs)
Thin wrapper around ``bitcoin.mktx(inputs, outputs)`` Args: inputs (dict): inputs in the form of ``{'output': 'txid:vout', 'value': amount in satoshi}`` outputs (dict): outputs in the form of ``{'address': to_address, 'value': amount in satoshi}`` ...
4.902575
4.260194
1.150787
netcode = 'XTN' if self.testnet else 'BTC' # TODO review # check if its a wif try: BIP32Node.from_text(master_password) return bitcoin.signall(tx, master_password) except (AttributeError, EncodingError): # if its not get the wif from ...
def sign_transaction(self, tx, master_password, path='')
Args: tx: hex transaction to sign master_password: master password for BIP32 wallets. Can be either a master_secret or a wif path (Optional[str]): optional path to the leaf address of the BIP32 wallet. This allows us to retrieve private key for the ...
5.588691
5.648866
0.989347
if not isinstance(self._service, BitcoinBlockrService): raise NotImplementedError('Currently only supported for "blockr.io"') return self._service.decode(tx)
def decode(self, tx)
Decodes the given transaction. Args: tx: hex of transaction Returns: decoded transaction .. note:: Only supported for blockr.io at the moment.
8.712558
6.094179
1.429652
# Request next integer in recid sequence. assert 'pid_value' not in kwargs kwargs['pid_value'] = str(RecordIdentifier.next()) kwargs.setdefault('status', cls.default_status) if object_type and object_uuid: kwargs['status'] = PIDStatus.REGISTERED retur...
def create(cls, object_type=None, object_uuid=None, **kwargs)
Create a new record identifier. Note: if the object_type and object_uuid values are passed, then the PID status will be automatically setted to :attr:`invenio_pidstore.models.PIDStatus.REGISTERED`. :param object_type: The object type. (Default: None.) :param object_uuid: The ob...
5.566626
3.935016
1.414639
return super(DataCiteProvider, cls).create( pid_value=pid_value, **kwargs)
def create(cls, pid_value, **kwargs)
Create a new record identifier. For more information about parameters, see :meth:`invenio_pidstore.providers.BaseProvider.create`. :param pid_value: Persistent identifier value. :params **kwargs: See :meth:`invenio_pidstore.providers.base.BaseProvider.create` extra ...
4.969666
4.114945
1.207711
# Only registered PIDs can be updated. try: self.pid.reserve() self.api.metadata_post(doc) except (DataCiteError, HttpError): logger.exception("Failed to reserve in DataCite", extra=dict(pid=self.pid)) raise ...
def reserve(self, doc)
Reserve a DOI (amounts to upload metadata, but not to mint). :param doc: Set metadata for DOI. :returns: `True` if is reserved successfully.
5.190089
5.051497
1.027436
try: self.pid.register() # Set metadata for DOI self.api.metadata_post(doc) # Mint DOI self.api.doi_post(self.pid.pid_value, url) except (DataCiteError, HttpError): logger.exception("Failed to register in DataCite", ...
def register(self, url, doc)
Register a DOI via the DataCite API. :param url: Specify the URL for the API. :param doc: Set metadata for DOI. :returns: `True` if is registered successfully.
4.192275
3.727086
1.124813
if self.pid.is_deleted(): logger.info("Reactivate in DataCite", extra=dict(pid=self.pid)) try: # Set metadata self.api.metadata_post(doc) self.api.doi_post(self.pid.pid_value, url) except (DataCiteError, HttpError)...
def update(self, url, doc)
Update metadata associated with a DOI. This can be called before/after a DOI is registered. :param doc: Set metadata for DOI. :returns: `True` if is updated successfully.
3.66068
3.610426
1.013919
try: if self.pid.is_new(): self.pid.delete() else: self.pid.delete() self.api.metadata_delete(self.pid.pid_value) except (DataCiteError, HttpError): logger.exception("Failed to delete in DataCite", ...
def delete(self)
Delete a registered DOI. If the PID is new then it's deleted only locally. Otherwise, also it's deleted also remotely. :returns: `True` if is deleted successfully.
3.644397
2.937503
1.240644
status = None try: try: self.api.doi_get(self.pid.pid_value) status = PIDStatus.REGISTERED except DataCiteGoneError: status = PIDStatus.DELETED except DataCiteNoContentError: status = PIDStatus....
def sync_status(self)
Synchronize DOI status DataCite MDS. :returns: `True` if is sync successfully.
2.641554
2.598307
1.016644
if len(hashes) == 1: return binascii.hexlify(bytearray(reversed(hashes[0]))) if len(hashes) % 2 == 1: hashes.append(hashes[-1]) parent_hashes = [] for i in range(0, len(hashes)-1, 2): first_round_hash = hashlib.sha256(hashes[i] + hashes[i+1]).digest() second_round_ha...
def merkleroot(hashes)
Args: hashes: reversed binary form of transactions hashes, e.g.: ``binascii.unhexlify(h)[::-1] for h in block['tx']]`` Returns: merkle root in hexadecimal form
1.948293
1.921507
1.01394
assert pid_value assert pid_type or cls.pid_type pid = PersistentIdentifier.create( pid_type or cls.pid_type, pid_value, pid_provider=cls.pid_provider, object_type=object_type, object_uuid=object_uuid, status=statu...
def create(cls, pid_type=None, pid_value=None, object_type=None, object_uuid=None, status=None, **kwargs)
Create a new instance for the given type and pid. :param pid_type: Persistent identifier type. (Default: None). :param pid_value: Persistent identifier value. (Default: None). :param status: Current PID status. (Default: :attr:`invenio_pidstore.models.PIDStatus.NEW`) :param ...
2.293628
2.707783
0.84705
return cls( PersistentIdentifier.get(pid_type or cls.pid_type, pid_value, pid_provider=cls.pid_provider), **kwargs)
def get(cls, pid_value, pid_type=None, **kwargs)
Get a persistent identifier for this provider. :param pid_type: Persistent identifier type. (Default: configured :attr:`invenio_pidstore.providers.base.BaseProvider.pid_type`) :param pid_value: Persistent identifier value. :param kwargs: See :meth:`invenio_pidstore.provi...
4.48461
4.837476
0.927056
cfg.CONF.register_opts(RAX_OPTS, group=config_group) self.logger = logging.getLogger(__name__) try: logging.register_options(cfg.CONF) except cfg.ArgsAlreadyParsedError: # pragma: no cover pass logging.setup(cfg.CONF, "flask_keystone") ...
def init_app(self, app, config_group="flask_keystone")
Iniitialize the Flask_Keystone module in an application factory. :param app: `flask.Flask` application to which to connect. :type app: `flask.Flask` :param str config_group: :class:`oslo_config.cfg.OptGroup` to which to attach. When initialized, the ext...
3.234044
3.244118
0.996895
roles = {} for keystone_role, flask_role in self.config.roles.items(): roles.setdefault(flask_role, set()).add(keystone_role) return roles
def _parse_roles(self)
Generate a dictionary for configured roles from oslo_config. Due to limitations in ini format, it's necessary to specify roles in a flatter format than a standard dictionary. This function serves to transform these roles into a standard python dictionary.
4.426645
4.040422
1.09559
def before_request(): identity_status = request.headers.get( "X-Identity-Status", "Invalid" ) if identity_status != "Confirmed": msg = ("Couldn't authenticate user '%s' with " "X-Identity-Status '%s'...
def _make_before_request(self)
Generate the before_request function to be added to the app. Currently this function is static, however it is very likely we will need to programmatically generate this function in the future.
3.347369
3.401155
0.984186
class User(UserBase): pass User.generate_has_role_function(self.roles) User.generate_is_role_functions(self.roles) return User
def _make_user_model(self)
Dynamically generate a User class for use with FlaskKeystone. :returns: a generated User class, inherited from :class:`flask_keystone.UserBase`. :rtype: class This User model is intended to work somewhat similarly to the User class that is created for Flask-Login, how...
9.283613
11.013863
0.842903
def wrap(f): @wraps(f) def wrapped_f(*args, **kwargs): if isinstance(roles, list): if any(current_user.has_role(role) for role in roles): return f(*args, **kwargs) elif isinstance(roles, str): ...
def requires_role(self, roles)
Require specific configured roles for access to a :mod:`flask` route. :param roles: Role or list of roles to test for access (only one role is required to pass). :type roles: str OR list(str) :raises: FlaskKeystoneForbidden This method will gate a particular endpo...
3.226453
2.894995
1.114493
@wraps(f) def wrapped_f(*args, **kwargs): if current_user.anonymous: msg = ("Rejected User '%s access to '%s' as user" " could not be authenticated.") self.logger.warn(msg % ( current_user.user_id, ...
def login_required(self, f)
Require a user to be validated by Identity to access an endpoint. :raises: FlaskKeystoneUnauthorized This method will gate a particular endpoint to only be accessed by :class:`FlaskKeystone.User`'s. This means that a valid token will need to be passed to grant access. If a User is not ...
5.349981
4.053259
1.319921
try: PersistentIdentifier.get(pidtype, value) return True except PIDDoesNotExistError: return False
def pid_exists(value, pidtype=None)
Check if a persistent identifier exists. :param value: The PID value. :param pidtype: The pid value (Default: None). :returns: `True` if the PID exists.
5.212002
5.359767
0.972431
assert name not in self.minters self.minters[name] = minter
def register_minter(self, name, minter)
Register a minter. :param name: Minter name. :param minter: The new minter.
3.18942
4.232553
0.753545
assert name not in self.fetchers self.fetchers[name] = fetcher
def register_fetcher(self, name, fetcher)
Register a fetcher. :param name: Fetcher name. :param fetcher: The new fetcher.
3.162914
4.141932
0.763632
for ep in pkg_resources.iter_entry_points(group=entry_point_group): self.register_minter(ep.name, ep.load())
def load_minters_entry_point_group(self, entry_point_group)
Load minters from an entry point group. :param entry_point_group: The entrypoint group.
2.858771
3.13195
0.912777
for ep in pkg_resources.iter_entry_points(group=entry_point_group): self.register_fetcher(ep.name, ep.load())
def load_fetchers_entry_point_group(self, entry_point_group)
Load fetchers from an entry point group. :param entry_point_group: The entrypoint group.
2.799222
3.118094
0.897735
self.init_config(app) # Initialize CLI app.cli.add_command(cmd) # Initialize logger app.config.setdefault('PIDSTORE_APP_LOGGER_HANDLERS', app.debug) if app.config['PIDSTORE_APP_LOGGER_HANDLERS']: for handler in app.logger.handlers: lo...
def init_app(self, app, minters_entry_point_group=None, fetchers_entry_point_group=None)
Flask application initialization. Initialize: * The CLI commands. * Initialize the logger (Default: `app.debug`). * Initialize the default admin object link endpoint. (Default: `{"rec": "recordmetadata.details_view"}` if `invenio-records` is installed, otherwi...
3.538303
2.12167
1.667697
response = self.make_request("importaddress", [address, account, rescan]) error = response.get('error') if error is not None: raise Exception(error) return response
def import_address(self, address, account="*", rescan=False)
param address = address to import param label= account name to use
3.024721
3.343924
0.904542
result = [(float(self.get_x()),float(self.get_y()))] result.append((float(self.get_x())+float(self.get_width()),float(self.get_y()))) result.append((float(self.get_x())+float(self.get_width()),float(self.get_y())+float(self.get_height()))) result.append((float(self.get_x()),floa...
def getEdgePoints(self)
Returns a list with the coordinates of the points at the edge of the rectangle as tuples. e.g.[(x1,y1),(x2,y2)] The sorting is counterclockwise starting with the lower left corner. Coordinates must be numbers or an exception will be thrown.
1.568902
1.454049
1.078989
result = [] result.append((float(self.get_x()) + float(self.get_rx()), float(self.get_y()) + float(self.get_ry()))) result.append((float(self.get_x()) + float(self.get_width()) - float(self.get_rx()), float(self.get_y()) + float(self.get_ry()))) result.append((float(self.get_x()...
def getInnerEdgePoints(self)
Returns a list with the coordinates of the points at the inner edge of a rounded rectangle as tuples. e.g.[(x1,y1),(x2,y2)] The sorting is counterclockwise starting with the lower left corner. Coordinates must be numbers or an exception will be thrown.
1.378346
1.291194
1.067498
return (float(self.get_x()) + float(self.get_width()), float(self.get_y()))
def getBottomRight(self)
Retrieves a tuple with the x,y coordinates of the lower right point of the rect. Requires the coordinates, width, height to be numbers
4.41012
3.683323
1.197321
return (float(self.get_x()), float(self.get_y())+ float(self.get_height()))
def getTopLeft(self)
Retrieves a tuple with the x,y coordinates of the upper left point of the rect. Requires the coordinates, width, height to be numbers
5.132694
4.074104
1.259834
return (float(self.get_x()) + float(self.get_width()), float(self.get_y()) + float(self.get_height()))
def getTopRight(self)
Retrieves a tuple with the x,y coordinates of the upper right point of the rect. Requires the coordinates, width, height to be numbers
2.839457
2.417218
1.17468
(x,y) = xxx_todo_changeme self.set_x(float(self.get_x()) + float(x)) self.set_y(float(self.get_y()) + float(y))
def moveToPoint(self, xxx_todo_changeme)
Moves the rect to the point x,y
2.179011
1.988063
1.096047
return (float(self.get_cx()) - float(self.get_r()), float(self.get_cy()) - float(self.get_r()))
def getBottomLeft(self)
Retrieves a tuple with the x,y coordinates of the lower left point of the circle. Requires the radius and the coordinates to be numbers
3.724134
2.917456
1.2765
return (float(self.get_cx()) + float(self.get_r()), float(self.get_cy()) - float(self.get_r()))
def getBottomRight(self)
Retrieves a tuple with the x,y coordinates of the lower right point of the circle. Requires the radius and the coordinates to be numbers
3.930279
3.094349
1.270147
return (float(self.get_cx()) - float(self.get_r()), float(self.get_cy()) + float(self.get_r()))
def getTopLeft(self)
Retrieves a tuple with the x,y coordinates of the upper left point of the circle. Requires the radius and the coordinates to be numbers
4.045774
3.257696
1.241913
return (float(self.get_cx()) + float(self.get_r()), float(self.get_cy()) + float(self.get_r()))
def getTopRight(self)
Retrieves a tuple with the x,y coordinates of the upper right point of the circle. Requires the radius and the coordinates to be numbers
3.737553
2.967257
1.259599
(x,y) = xxx_todo_changeme1 self.set_cx(float(self.get_cx()) + float(x)) self.set_cy(float(self.get_cy()) + float(y))
def moveToPoint(self, xxx_todo_changeme1)
Moves the circle to the point x,y
2.468854
2.11902
1.165092
return (float(self.get_cx()) - float(self.get_rx()), float(self.get_cy()) - float(self.get_ry()))
def getBottomLeft(self)
Retrieves a tuple with the x,y coordinates of the lower left point of the ellipse. Requires the radius and the coordinates to be numbers
3.695832
2.946525
1.254302
return (float(self.get_cx()) + float(self.get_rx()), float(self.get_cy()) - float(self.get_ry()))
def getBottomRight(self)
Retrieves a tuple with the x,y coordinates of the lower right point of the ellipse. Requires the radius and the coordinates to be numbers
3.888865
3.178652
1.223432
return (float(self.get_cx()) - float(self.get_rx()), float(self.get_cy()) + float(self.get_ry()))
def getTopLeft(self)
Retrieves a tuple with the x,y coordinates of the upper left point of the ellipse. Requires the radius and the coordinates to be numbers
4.077123
3.319525
1.228225
return (float(self.get_cx()) + float(self.get_rx()), float(self.get_cy()) + float(self.get_ry()))
def getTopRight(self)
Retrieves a tuple with the x,y coordinates of the upper right point of the ellipse. Requires the radius and the coordinates to be numbers
3.594029
2.965405
1.211986
x1 = float(self.get_x1()) x2 = float(self.get_x2()) y1 = float(self.get_y1()) y2 = float(self.get_y2()) if x1 < x2: if y1 < y2: return (x1, y1) else: return (x1, y2) else: if y1 < y2: ...
def getBottomLeft(self)
Retrieves the the bottom left coordinate of the line as tuple. Coordinates must be numbers.
1.546419
1.478422
1.045993
(x,y) = xxx_todo_changeme2 self.set_x1(float(self.get_x1()) + float(x)) self.set_x2(float(self.get_x2()) + float(x)) self.set_y1(float(self.get_y1()) + float(y)) self.set_y2(float(self.get_y2()) + float(y))
def moveToPoint(self, xxx_todo_changeme2)
Moves the line to the point x,y
1.596578
1.495458
1.067618
style_dict = {'fill':fill, 'stroke-width':strokewidth, 'stroke':stroke} myStyle = StyleBuilder(style_dict) c = Circle(cx, cy, r) c.set_style(myStyle.getStyle()) return c
def createCircle(self, cx, cy, r, strokewidth=1, stroke='black', fill='none')
Creates a circle @type cx: string or int @param cx: starting x-coordinate @type cy: string or int @param cy: starting y-coordinate @type r: string or int @param r: radius @type strokewidth: string or int @param strokewidth: width of the pen use...
3.409965
3.941916
0.865053
style_dict = {'fill':fill, 'stroke-width':strokewidth, 'stroke':stroke} myStyle = StyleBuilder(style_dict) e = Ellipse(cx, cy, rx, ry) e.set_style(myStyle.getStyle()) return e
def createEllipse(self, cx, cy, rx, ry, strokewidth=1, stroke='black', fill='none')
Creates an ellipse @type cx: string or int @param cx: starting x-coordinate @type cy: string or int @param cy: starting y-coordinate @type rx: string or int @param rx: radius in x direction @type ry: string or int @param ry: radius in y directi...
3.309784
3.85235
0.85916
style_dict = {'fill':fill, 'stroke-width':strokewidth, 'stroke':stroke} myStyle = StyleBuilder(style_dict) r = Rect(x, y, width, height, rx, ry) r.set_style(myStyle.getStyle()) return r
def createRect(self, x, y, width, height, rx=None, ry=None, strokewidth=1, stroke='black', fill='none')
Creates a Rectangle @type x: string or int @param x: starting x-coordinate @type y: string or int @param y: starting y-coordinate @type width: string or int @param width: width of the rectangle @type height: string or int @param height: height...
3.187347
3.65485
0.872087
style_dict = {'fill':fill, 'stroke-width':strokewidth, 'stroke':stroke} myStyle = StyleBuilder(style_dict) p = Polygon(points=points) p.set_style(myStyle.getStyle()) return p
def createPolygon(self, points, strokewidth=1, stroke='black', fill='none')
Creates a Polygon @type points: string in the form "x1,y1 x2,y2 x3,y3" @param points: all points relevant to the polygon @type strokewidth: string or int @param strokewidth: width of the pen used to draw @type stroke: string (either css constants like "black" or numerical va...
3.511207
4.454273
0.788278
style_dict = {'fill':'none', 'stroke-width':strokewidth, 'stroke':stroke} myStyle = StyleBuilder(style_dict) p = Polyline(points=points) p.set_style(myStyle.getStyle()) return p
def createPolyline(self, points, strokewidth=1, stroke='black')
Creates a Polyline @type points: string in the form "x1,y1 x2,y2 x3,y3" @param points: all points relevant to the polygon @type strokewidth: string or int @param strokewidth: width of the pen used to draw @type stroke: string (either css constants like "black" or numerical v...
3.558166
4.396895
0.809245
style_dict = {'stroke-width':strokewidth, 'stroke':stroke} myStyle = StyleBuilder(style_dict) l = Line(x1, y1, x2, y2) l.set_style(myStyle.getStyle()) return l
def createLine(self, x1, y1, x2, y2, strokewidth=1, stroke="black")
Creates a line @type x1: string or int @param x1: starting x-coordinate @type y1: string or int @param y1: starting y-coordinate @type x2: string or int @param x2: ending x-coordinate @type y2: string or int @param y2: ending y-coordinate @...
3.332326
3.894872
0.855567
points = "" for tuple in arrayOfPointTuples: points += str(tuple[0]) + "," + str(tuple[1]) + " " return points
def convertTupleArrayToPoints(self, arrayOfPointTuples)
Method used to convert an array of tuples (x,y) into a string suitable for createPolygon or createPolyline @type arrayOfPointTuples: An array containing tuples eg.[(x1,y1),(x2,y2] @param arrayOfPointTuples: All points needed to create the shape @return a string in the form "x1,y1 x2,y2...
2.69879
2.267909
1.189991
# All argument types must be str. rtext = [str(f) for f in text] return COLORIZE_FORMAT.format( _to_int(bg), _to_int(base), _to_int(fg), ''.join(rtext) )
def colorize(bg, base, fg, *text)
colorize(bg, base, fg, *text)
5.139612
5.208219
0.986827
match = re.match('(.*)\033\[[0-9;]+m(.+?)\033\[0m(.*)', text) try: return ''.join(match.groups()) except: return text
def uncolorize(text)
uncolorize(text)
3.246229
3.485914
0.931242
return re.sub(kword, colorize(BgColor.Null, Base.Null, color, kword), text)
def tr(text, kword, color)
tr(text, keyword, color)
16.190027
16.374443
0.988738
s='' for _t in text: if _t in kword: s += colorize(BgColor.Null, Base.Null, color, _t) else: s += _t return s
def tr_iter(text, kword, color)
tr_iter(text, kword, color)
7.143461
7.160012
0.997688
print( colorize( kwargs.get('bg') or BgColor.Null, kwargs.get('base') or Base.Null, kwargs.get('fg') or FgColor.Null, *text ), file=kwargs.get('file') or sys.stdout )
def cprint(*text, **kwargs)
cprint(*text, **keywordargs)
4.453587
4.350398
1.023719
if isinstance(data, unicode): data = data.encode('utf8') elif not isinstance(data, basestring): raise ValueError('data argument must be a string.') version = int(version) if level not in levels: raise ValueError('Invalid error-correction level.') if hint not in hints: ...
def encode(data, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8, case_sensitive=True)
Creates a QR-Code from string data. Args: data: string: The data to encode in a QR-code. If a unicode string is supplied, it will be encoded in UTF-8. version: int: The minimum version to use. If set to 0, the library picks the smallest version that the data fits in. level...
2.528011
2.124216
1.190091
version, src_size, im = encode(data, version, level, hint, case_sensitive) if size < src_size: size = src_size qr_size = (size / src_size) * src_size im = im.resize((qr_size, qr_size), Image.NEAREST) pad = (size - qr_size) / 2 ret = Image.new("L", (size, size), 255) ret.paste(im, ...
def encode_scaled(data, size, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8, case_sensitive=True)
Creates a QR-code from string data, resized to the specified dimensions. Args: data: string: The data to encode in a QR-code. If a unicode string is supplied, it will be encoded in UTF-8. size: int: Output size. If this is not an exact multiple of the QR-code's dimensions, padding w...
2.881113
2.871904
1.003207
perp = Vector(-self.y, self.x) angle = angle * math.pi / 180.0 c, s = math.cos(angle), math.sin(angle) return Vector(self.x * c + perp.x * s, self.y * c + perp.y * s)
def rotate(self, angle)
Rotates self counterclockwise by angle (the angle must be given in a 360 degree system)
2.141102
2.129678
1.005364
self._position = vector if self.isPenDown(): self._pointsOfPolyline.append(self._position)
def moveTo(self, vector)
Moves the turtle to the new position. Orientation is kept as it is. If the pen is lowered it will also add to the currently drawn polyline.
14.853918
7.15597
2.075738
if self._penDown==True: self._penDown = False self._addPolylineToElements()
def penUp(self)
Raises the pen. Any movement will not draw lines till pen is lowered again.
15.775512
11.749307
1.342676
self._position = self._position + self._orient * distance if self.isPenDown(): x = round(self._position.x, 2) y = round(self._position.y, 2) self._pointsOfPolyline.append(Vector(x, y))
def _move(self, distance)
Moves the turtle by distance in the direction it is facing. If the pen is lowered it will also add to the currently drawn polyline.
5.356179
3.960085
1.352541
if (len(self._pointsOfPolyline) > 1): s = '' for point in self._pointsOfPolyline: s += str(point) + ' '#str(point.x) + ',' + str(point.y) + ' ' p = Polyline(s) p.set_style('fill:' + self.fill + '; stroke:' + self.stroke + '; stroke-width:'...
def _addPolylineToElements(self)
Creates a new Polyline element that will be used for future movement/drawing. The old one (if filled) will be stored on the movement stack.
3.331745
3.071442
1.084749
s = '' for element in self._svgElements: s += element.getXML() return s
def getXML(self)
Retrieves the pysvg elements that make up the turtles path and returns them as String in an xml representation.
7.401702
4.50261
1.643869
for element in self.getSVGElements(): svgContainer.addElement(element) return svgContainer
def addTurtlePathToSVG(self, svgContainer)
Adds the paths of the turtle to an existing svg container.
5.04368
5.023789
1.003959
self._valid_template() context.update({ "csrf_token_value": get_token(self.request) }) return render_to_string(self.get_template_names(), context)
def _get_content(self, context)
Add the csrf_token_value because the mixin use render_to_string and not render.
6.11554
3.816984
1.602192
new_path = k_paths.normpath(path) if keep_trailing and path.endswith("/") and not new_path.endswith("/"): new_path = new_path + "/" if not new_path.startswith('/'): return '/' + new_path return new_path
def normpath(path, keep_trailing=False)
Really normalize the path by adding a missing leading slash.
2.979037
2.900586
1.027046
encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filenames: if path.splitext(filename)[1] == ".md": try: import pypandoc buf.append(pypandoc.convert_file(filename, 'rst')) continue ...
def read(*filenames, **kwargs)
Read file contents into string. Used by setup.py to concatenate long_description. :param string filenames: Files to be read and concatenated. :rtype: string
2.083202
2.06214
1.010214
try: with db.session.begin_nested(): obj = cls(pid_type=pid_type, pid_value=pid_value, pid_provider=pid_provider, status=status) if object_type and object_uuid: ...
def create(cls, pid_type, pid_value, pid_provider=None, status=PIDStatus.NEW, object_type=None, object_uuid=None,)
Create a new persistent identifier with specific type and value. :param pid_type: Persistent identifier type. :param pid_value: Persistent identifier value. :param pid_provider: Persistent identifier provider. (default: None). :param status: Current PID status. (Default: :at...
1.505655
1.567388
0.960614
try: args = dict(pid_type=pid_type, pid_value=six.text_type(pid_value)) if pid_provider: args['pid_provider'] = pid_provider return cls.query.filter_by(**args).one() except NoResultFound: raise PIDDoesNotExistError(pid_type, pid_va...
def get(cls, pid_type, pid_value, pid_provider=None)
Get persistent identifier. :param pid_type: Persistent identifier type. :param pid_value: Persistent identifier value. :param pid_provider: Persistent identifier provider. (default: None). :raises: :exc:`invenio_pidstore.errors.PIDDoesNotExistError` if no PID is found. ...
2.016215
2.121235
0.950491
try: return cls.query.filter_by( pid_type=pid_type, object_type=object_type, object_uuid=object_uuid ).one() except NoResultFound: raise PIDDoesNotExistError(pid_type, None)
def get_by_object(cls, pid_type, object_type, object_uuid)
Get a persistent identifier for a given object. :param pid_type: Persistent identifier type. :param object_type: The object type is a string that identify its type. :param object_uuid: The object UUID. :raises invenio_pidstore.errors.PIDDoesNotExistError: If no PID is found....
2.1305
2.202538
0.967293
if object_type is not None: if self.object_type == object_type: return self.object_uuid else: return None return self.object_uuid
def get_assigned_object(self, object_type=None)
Return the current assigned object UUID. :param object_type: If it's specified, returns only if the PID object_type is the same, otherwise returns None. (default: None). :returns: The object UUID.
2.888462
2.8264
1.021958
if self.is_deleted(): raise PIDInvalidAction( "You cannot assign objects to a deleted/redirected persistent" " identifier." ) if not isinstance(object_uuid, uuid.UUID): object_uuid = uuid.UUID(object_uuid) if self.obj...
def assign(self, object_type, object_uuid, overwrite=False)
Assign this persistent identifier to a given object. Note, the persistent identifier must first have been reserved. Also, if an existing object is already assigned to the pid, it will raise an exception unless overwrite=True. :param object_type: The object type is a string that identif...
2.648073
2.375045
1.114957
if self.object_uuid is None and self.object_type is None: return True try: with db.session.begin_nested(): if self.is_redirected(): db.session.delete(Redirect.query.get(self.object_uuid)) # Only registered PIDs can...
def unassign(self)
Unassign the registered object. Note: Only registered PIDs can be redirected so we set it back to registered. :returns: `True` if the PID is successfully unassigned.
4.232255
3.239799
1.306333
if not (self.is_registered() or self.is_redirected()): raise PIDInvalidAction("Persistent identifier is not registered.") try: with db.session.begin_nested(): if self.is_redirected(): r = Redirect.query.get(self.object_uuid) ...
def redirect(self, pid)
Redirect persistent identifier to another persistent identifier. :param pid: The :class:`invenio_pidstore.models.PersistentIdentifier` where redirect the PID. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not registered or is not already redirecting to another ...
3.276064
2.68118
1.221874
if not (self.is_new() or self.is_reserved()): raise PIDInvalidAction( "Persistent identifier is not new or reserved.") try: with db.session.begin_nested(): self.status = PIDStatus.RESERVED db.session.add(self) exce...
def reserve(self)
Reserve the persistent identifier. Note, the reserve method may be called multiple times, even if it was already reserved. :raises: :exc:`invenio_pidstore.errors.PIDInvalidAction` if the PID is not new or is not already reserved a PID. :returns: `True` if the PID is success...
3.927114
2.858835
1.373676
if self.is_registered() or self.is_deleted() or self.is_redirected(): raise PIDInvalidAction( "Persistent identifier has already been registered" " or is deleted.") try: with db.session.begin_nested(): self.status = PIDSta...
def register(self)
Register the persistent identifier with the provider. :raises invenio_pidstore.errors.PIDInvalidAction: If the PID is not already registered or is deleted or is a redirection to another PID. :returns: `True` if the PID is successfully register.
4.092081
2.888309
1.416774
removed = False try: with db.session.begin_nested(): if self.is_new(): # New persistent identifier which haven't been registered # yet. db.session.delete(self) removed = True ...
def delete(self)
Delete the persistent identifier. If the persistent identifier haven't been registered yet, it is removed from the database. Otherwise, it's marked as :attr:`invenio_pidstore.models.PIDStatus.DELETED`. :returns: `True` if the PID is successfully removed.
3.821199
3.104824
1.23073
if self.status == status: return True try: with db.session.begin_nested(): self.status = status db.session.add(self) except SQLAlchemyError: logger.exception("Failed to sync status {0}.".format(status), ...
def sync_status(self, status)
Synchronize persistent identifier status. Used when the provider uses an external service, which might have been modified outside of our system. :param status: The new status to set. :returns: `True` if the PID is successfully sync.
3.515057
3.046765
1.153701
try: with db.session.begin_nested(): obj = cls() db.session.add(obj) except IntegrityError: # pragma: no cover with db.session.begin_nested(): # Someone has likely modified the table without using the # mod...
def next(cls)
Return next available record identifier.
5.570269
4.867656
1.144343
max_recid = db.session.query(func.max(cls.recid)).scalar() return max_recid if max_recid else 0
def max(cls)
Get max record identifier.
3.413718
2.625551
1.300191
if db.engine.dialect.name == 'postgresql': # pragma: no cover db.session.execute( "SELECT setval(pg_get_serial_sequence(" "'{0}', 'recid'), :newval)".format( cls.__tablename__), dict(newval=val))
def _set_sequence(cls, val)
Internal function to reset sequence to specific value. Note: this function is for PostgreSQL compatibility. :param val: The value to be set.
4.359564
4.670821
0.933361
with db.session.begin_nested(): obj = cls(recid=val) db.session.add(obj) cls._set_sequence(cls.max())
def insert(cls, val)
Insert a record identifier. :param val: The `recid` column value to insert.
7.1878
6.540199
1.099019
op.create_table( 'pidstore_pid', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), sa.Column('id', sa.Integer(), nullable=False), sa.Column('pid_type', sa.String(length=6), nullable=False), sa.Column('pid_va...
def upgrade()
Upgrade database.
1.593465
1.59178
1.001058
pid = PersistentIdentifier.get(self.pid_type, pid_value) if pid.is_new() or pid.is_reserved(): raise PIDUnregistered(pid) if pid.is_deleted(): obj_id = pid.get_assigned_object(object_type=self.object_type) try: obj = self.object_gett...
def resolve(self, pid_value)
Resolve a persistent identifier to an internal object. :param pid_value: Persistent identifier. :returns: A tuple containing (pid, object).
2.757742
2.731777
1.009505
ws = self.conn.sheets_service.AddWorksheet(title, 10, 10, self.id) self._wsf = None return Sheet(self, ws)
def create_sheet(self, title)
Create a sheet with the given title. This does not check if another sheet by the same name already exists.
10.426069
9.738562
1.070596
spreadsheet = cls.by_title(title, conn=conn, google_user=google_user, google_password=google_password) if spreadsheet is None: spreadsheet = cls.create(title, conn=conn, google_user=google_user, google_password=...
def open(cls, title, conn=None, google_user=None, google_password=None)
Open the spreadsheet named ``title``. If no spreadsheet with that name exists, a new one will be created.
2.070246
1.95608
1.058365