Search is not available for this dataset
text stringlengths 75 104k |
|---|
def add_netnode_plugin_name(plugin_name):
"""
Add the given plugin name to the list of plugin names registered in
the current IDB.
Note that this implicitly uses the open IDB via the idc iterface.
"""
current_names = set(get_netnode_plugin_names())
if plugin_name in current_names:
... |
def del_netnode_plugin_name(plugin_name):
"""
Remove the given plugin name to the list of plugin names registered in
the current IDB.
Note that this implicitly uses the open IDB via the idc iterface.
"""
current_names = set(get_netnode_plugin_names())
if plugin_name not in current_names:
... |
def import_settings(settings, config_path):
"""
Import settings from the given file system path to given settings instance.
type settings: IDASettingsInterface
type config_path: str
"""
other = QtCore.QSettings(config_path, QtCore.QSettings.IniFormat)
for k in other.allKeys():
setti... |
def export_settings(settings, config_path):
"""
Export the given settings instance to the given file system path.
type settings: IDASettingsInterface
type config_path: str
"""
other = QtCore.QSettings(config_path, QtCore.QSettings.IniFormat)
for k, v in settings.iteritems():
other.s... |
def directory(self):
"""
Fetch the IDASettings instance for the curren plugin with directory scope.
rtype: IDASettingsInterface
"""
if self._config_directory is None:
ensure_ida_loaded()
return DirectoryIDASettings(self._plugin_name, directory=self._config_di... |
def get_value(self, key):
"""
Fetch the settings value with the highest precedence for the given
key, or raise KeyError.
Precedence:
- IDB scope
- directory scope
- user scope
- system scope
type key: basestring
rtype value: Union... |
def iterkeys(self):
"""
Enumerate the keys found at any scope for the current plugin.
rtype: Generator[str]
"""
visited_keys = set()
try:
for key in self.idb.iterkeys():
if key not in visited_keys:
yield key
... |
def get_directory_plugin_names(config_directory=None):
"""
Get the names of all plugins at the directory scope.
Provide a config directory path to use this method outside of IDA.
As this is a static method, you can call the directly on IDASettings:
import ida_settings
... |
def simple_error_handler(exc, *args):
"""
Returns the response that should be used for any given exception.
By default we handle the REST framework `APIException`, and also
Django's builtin `Http404` and `PermissionDenied` exceptions.
Any unhandled exceptions may return `None`, which will cause a ... |
def table(name, auth=None, eager=True):
"""Returns a given table for the given user."""
auth = auth or []
dynamodb = boto.connect_dynamodb(*auth)
table = dynamodb.get_table(name)
return Table(table=table, eager=eager) |
def tables(auth=None, eager=True):
"""Returns a list of tables for the given user."""
auth = auth or []
dynamodb = boto.connect_dynamodb(*auth)
return [table(t, auth, eager=eager) for t in dynamodb.list_tables()] |
def fetch_items(self, category, **kwargs):
"""Fetch packages and summary from Crates.io
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
from_date = kwargs['from_date']
if category == CATEGORY_C... |
def metadata_id(item):
"""Extracts the identifier from an item depending on its type."""
if Crates.metadata_category(item) == CATEGORY_CRATES:
return str(item['id'])
else:
ts = item['fetched_on']
ts = str_to_datetime(ts)
return str(ts.timestamp()) |
def metadata_updated_on(item):
"""Extracts the update time from an item.
Depending on the item, the timestamp is extracted from the
'updated_at' or 'fetched_on' fields.
This date is converted to UNIX timestamp format.
:param item: item generated by the backend
:returns... |
def _init_client(self, from_archive=False):
"""Init client"""
return CratesClient(self.sleep_time, self.archive, from_archive) |
def __fetch_summary(self):
"""Fetch summary"""
raw_summary = self.client.summary()
summary = json.loads(raw_summary)
summary['fetched_on'] = str(datetime_utcnow())
yield summary |
def __fetch_crates(self, from_date):
"""Fetch crates"""
from_date = datetime_to_utc(from_date)
crates_groups = self.client.crates()
for raw_crates in crates_groups:
crates = json.loads(raw_crates)
for crate_container in crates['crates']:
if st... |
def __fetch_crate_owner_team(self, crate_id):
"""Get crate team owner"""
raw_owner_team = self.client.crate_attribute(crate_id, 'owner_team')
owner_team = json.loads(raw_owner_team)
return owner_team |
def __fetch_crate_owner_user(self, crate_id):
"""Get crate user owners"""
raw_owner_user = self.client.crate_attribute(crate_id, 'owner_user')
owner_user = json.loads(raw_owner_user)
return owner_user |
def __fetch_crate_versions(self, crate_id):
"""Get crate versions data"""
raw_versions = self.client.crate_attribute(crate_id, "versions")
version_downloads = json.loads(raw_versions)
return version_downloads |
def __fetch_crate_version_downloads(self, crate_id):
"""Get crate version downloads"""
raw_version_downloads = self.client.crate_attribute(crate_id, "downloads")
version_downloads = json.loads(raw_version_downloads)
return version_downloads |
def __fetch_crate_data(self, crate_id):
"""Get crate data"""
raw_crate = self.client.crate(crate_id)
crate = json.loads(raw_crate)
return crate['crate'] |
def summary(self):
"""Get Crates.io summary"""
path = urijoin(CRATES_API_URL, CATEGORY_SUMMARY)
raw_content = self.fetch(path)
return raw_content |
def crates(self, from_page=1):
"""Get crates in alphabetical order"""
path = urijoin(CRATES_API_URL, CATEGORY_CRATES)
raw_crates = self.__fetch_items(path, from_page)
return raw_crates |
def crate(self, crate_id):
"""Get a crate by its ID"""
path = urijoin(CRATES_API_URL, CATEGORY_CRATES, crate_id)
raw_crate = self.fetch(path)
return raw_crate |
def crate_attribute(self, crate_id, attribute):
"""Get crate attribute"""
path = urijoin(CRATES_API_URL, CATEGORY_CRATES, crate_id, attribute)
raw_attribute_data = self.fetch(path)
return raw_attribute_data |
def __fetch_items(self, path, page=1):
"""Return the items from Crates.io API using pagination"""
fetch_data = True
parsed_crates = 0
total_crates = 0
while fetch_data:
logger.debug("Fetching page: %i", page)
try:
payload = {'sort': 'alp... |
def fetch(self, url, payload=None):
"""Return the textual content associated to the Response object"""
response = super().fetch(url, payload=payload)
return response.text |
def fetch(self, category=CATEGORY_QUESTION, offset=DEFAULT_OFFSET):
"""Fetch questions from the Kitsune url.
:param category: the category of items to fetch
:offset: obtain questions after offset
:returns: a generator of questions
"""
if not offset:
offset = ... |
def fetch_items(self, category, **kwargs):
"""Fetch questions from the Kitsune url
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
offset = kwargs['offset']
logger.info("Looking for questions a... |
def _init_client(self, from_archive=False):
"""Init client"""
return KitsuneClient(self.url, self.archive, from_archive) |
def get_questions(self, offset=None):
"""Retrieve questions from older to newer updated starting offset"""
page = KitsuneClient.FIRST_PAGE
if offset:
page += int(offset / KitsuneClient.ITEMS_PER_PAGE)
while True:
api_questions_url = urijoin(self.base_url, '/que... |
def get_question_answers(self, question_id):
"""Retrieve all answers for a question from older to newer (updated)"""
page = KitsuneClient.FIRST_PAGE
while True:
api_answers_url = urijoin(self.base_url, '/answer') + '/'
params = {
"page": page,
... |
def fetch(self, url, params):
"""Return the textual content associated to the Response object"""
logger.debug("Kitsune client calls API: %s params: %s",
url, str(params))
response = super().fetch(url, payload=params)
return response.text |
def fetch(self, category=CATEGORY_EVENT, offset=REMO_DEFAULT_OFFSET):
"""Fetch items from the ReMo url.
The method retrieves, from a ReMo URL, the set of items
of the given `category`.
:param category: the category of items to fetch
:param offset: obtain items after offset
... |
def fetch_items(self, category, **kwargs):
"""Fetch items
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
offset = kwargs['offset']
logger.info("Looking for events at url '%s' of %s category an... |
def metadata_updated_on(item):
"""Extracts the update time from a ReMo item.
The timestamp is extracted from 'end' field.
This date is converted to a perceval format using a float value.
:param item: item generated by the backend
:returns: a UNIX timestamp
"""
... |
def metadata_category(item):
"""Extracts the category from a ReMo item.
This backend generates items types 'event', 'activity'
or 'user'. To guess the type of item, the code will look
for unique fields.
"""
if 'estimated_attendance' in item:
category = CATEGO... |
def _init_client(self, from_archive=False):
"""Init client"""
return ReMoClient(self.url, self.archive, from_archive) |
def get_items(self, category=CATEGORY_EVENT, offset=REMO_DEFAULT_OFFSET):
"""Retrieve all items for category using pagination """
more = True # There are more items to be processed
next_uri = None # URI for the next items page query
page = ReMoClient.FIRST_PAGE
page += int(off... |
def buffer_list(self):
"""
The buffer list this instance operates on.
Only available in mode != AIOBLOCK_MODE_POLL.
Changes on a submitted transfer are not fully applied until its
next submission: kernel will still be using original buffer list.
"""
if self._ioc... |
def io_priority(self):
"""
IO priority for this instance.
"""
return (
self._iocb.aio_reqprio
if self._iocb.u.c.flags & libaio.IOCB_FLAG_IOPRIO else
None
) |
def close(self):
"""
Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context.
"""
if self._ctx is not None:
# Note: same as io_destroy
self._io_queue_release(self._ctx)
del self._ctx |
def submit(self, block_list):
"""
Submits transfers.
block_list (list of AIOBlock)
The IO blocks to hand off to kernel.
Returns the number of successfully submitted blocks.
"""
# io_submit ioctl will only return an error for issues with the first
# t... |
def cancel(self, block):
"""
Cancel an IO block.
block (AIOBlock)
The IO block to cancel.
Returns cancelled block's event data (see getEvents), or None if the
kernel returned EINPROGRESS. In the latter case, event completion will
happen on a later getEvents ... |
def cancelAll(self):
"""
Cancel all submitted IO blocks.
Blocks until all submitted transfers have been finalised.
Submitting more transfers or processing completion events while this
method is running produces undefined behaviour.
Returns the list of values returned by ... |
def getEvents(self, min_nr=1, nr=None, timeout=None):
"""
Returns a list of event data from submitted IO blocks.
min_nr (int, None)
When timeout is None, minimum number of events to collect before
returning.
If None, waits for all submitted events.
nr... |
def fetch(self, category=CATEGORY_EVENT):
"""Fetch events from the MozillaClub URL.
The method retrieves, from a MozillaClub URL, the
events. The data is a Google spreadsheet retrieved using
the feed API REST.
:param category: the category of items to fetch
:returns: a... |
def fetch_items(self, category, **kwargs):
"""Fetch events
:param category: the category of items to fetch
:param kwargs: backend arguments
:returns: a generator of items
"""
logger.info("Looking for events at url '%s'", self.url)
nevents = 0 # number of event... |
def _init_client(self, from_archive=False):
"""Init client"""
return MozillaClubClient(self.url, self.archive, from_archive) |
def get_cells(self):
"""Retrieve all cells from the spreadsheet."""
logger.info("Retrieving all cells spreadsheet data ...")
logger.debug("MozillaClub client calls API: %s", self.base_url)
raw_cells = self.fetch(self.base_url)
return raw_cells.text |
def parse(self):
"""Parse the MozillaClub spreadsheet feed cells json."""
nevents_wrong = 0
feed_json = json.loads(self.feed)
if 'entry' not in feed_json['feed']:
return
self.cells = feed_json['feed']['entry']
self.ncell = 0
event_fields = self.__... |
def __get_event_fields(self):
"""Get the events fields (columns) from the cells received."""
event_fields = {}
# The cells in the first row are the column names
# Check that the columns names are the same we have as template
# Create the event template from the data retrieved
... |
def get_data_files(dirname):
"""Return data files in directory *dirname*"""
flist = []
for dirpath, _dirnames, filenames in os.walk(dirname):
for fname in filenames:
flist.append(osp.join(dirpath, fname))
return flist |
def md5(file_path):
"""Calculates the md5-hash of the file.
:param file_path: full path to the file.
"""
hasher = hashlib.md5()
with open(file_path, 'rb') as f:
while True:
buf = f.read(BLOCKSIZE)
if not buf:
break
while len(buf... |
def size(full_path):
"""Shows file size.
:param full_path: full path to the file.
"""
file_size = os.path.getsize(full_path)
str_file_size = str(file_size)
print(str_file_size, 'b')
# Show size in b, kb, mb or gb depending on the dimension
if len(str_file_size) >= 10:
... |
def calculate(directory):
"""Split the tuple (obtained from scan) to separate files.
Alternately send full paths to the files in md5 and call it.
:param directory: tuple of files in the directory."""
# Set correct slashes for the OS
if sys.platform == 'windows':
slash = '\\'
... |
def scan(tree):
"""Scan the directory and send the obtained tuple to calculate.
:param tree: path to file or directory"""
tree = os.path.normpath(tree)
assert os.path.exists(tree), "#Error. The path '{}' is" \
" invalid or doesn't exist.".format(str(tree))
... |
def export_formats(self, pid_type):
"""List of export formats."""
if pid_type not in self._export_formats:
fmts = self.app.config.get('RECORDS_UI_EXPORT_FORMATS', {}).get(
pid_type, {})
self._export_formats[pid_type] = sorted(
[(k, v) for k, v in f... |
def permission_factory(self):
"""Load default permission factory."""
if self._permission_factory is None:
imp = self.app.config['RECORDS_UI_DEFAULT_PERMISSION_FACTORY']
self._permission_factory = obj_or_import_string(imp)
return self._permission_factory |
def init_app(self, app):
"""Flask application initialization.
:param app: The Flask application.
"""
self.init_config(app)
app.extensions['invenio-records-ui'] = _RecordUIState(app) |
def create_blueprint(endpoints):
"""Create Invenio-Records-UI blueprint.
The factory installs one URL route per endpoint defined, and adds an
error handler for rendering tombstones.
:param endpoints: Dictionary of endpoints to be installed. See usage
documentation for further details.
:ret... |
def create_url_rule(endpoint, route=None, pid_type=None, template=None,
permission_factory_imp=None, view_imp=None,
record_class=None, methods=None):
"""Create Werkzeug URL rule for a specific endpoint.
The method takes care of creating a persistent identifier resolver
... |
def record_view(pid_value=None, resolver=None, template=None,
permission_factory=None, view_method=None, **kwargs):
"""Display record view.
The two parameters ``resolver`` and ``template`` should not be included
in the URL rule, but instead set by creating a partially evaluated function
... |
def default_view_method(pid, record, template=None, **kwargs):
r"""Display default view.
Sends record_viewed signal and renders template.
:param pid: PID object.
:param record: Record object.
:param template: Template to render.
:param \*\*kwargs: Additional view arguments based on URL rule.
... |
def export(pid, record, template=None, **kwargs):
r"""Record serialization view.
Serializes record with given format and renders record export template.
:param pid: PID object.
:param record: Record object.
:param template: Template to render.
:param \*\*kwargs: Additional view arguments based... |
def records():
"""Load test data fixture."""
import uuid
from invenio_records.api import Record
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
# Record 1 - Live record
with db.session.begin_nested():
pid1 = PersistentIdentifier.create(
'recid', '1', obje... |
def time_callable(self, name, target, rate=None, args=(), kwargs={}):
# type: (str, Callable, float, Tuple, Dict) -> Chronometer
"""Send a Timer metric calculating duration of execution of the provided callable"""
assert callable(target)
if rate is None:
rate = self._rate
... |
def close(self):
# type: () -> None
"""Close the socket to free system resources.
After the socket is closed, further operations with socket
will fail. Multiple calls to close will have no effect.
"""
if self._closed:
return
self._socket.close()
... |
def remove_client(self, client):
# type: (object) -> None
"""Remove the client from the users of the socket.
If there are no more clients for the socket, it
will close automatically.
"""
try:
self._clients.remove(id(client))
except ValueError:
... |
def increment(self, name, count=1, rate=1):
# type: (str, int, float) -> None
"""Increment a Counter metric"""
if self._should_send_metric(name, rate):
self._request(
Counter(
self._create_metric_name_for_request(name),
int(cou... |
def timing(self, name, milliseconds, rate=1):
# type: (str, float, float) -> None
"""Send a Timer metric with the specified duration in milliseconds"""
if self._should_send_metric(name, rate):
milliseconds = int(milliseconds)
self._request(
Timer(
... |
def timing_since(self, name, start_time, rate=1):
# type: (str, Union[float, datetime], float) -> None
"""Send a Timer metric calculating the duration from the start time"""
duration = 0 # type: float
if isinstance(start_time, datetime):
duration = (datetime.now(start_time.t... |
def gauge(self, name, value, rate=1):
# type: (str, float, float) -> None
"""Send a Gauge metric with the specified value"""
if self._should_send_metric(name, rate):
if not is_numeric(value):
value = float(value)
self._request(
Gauge(
... |
def gauge_delta(self, name, delta, rate=1):
# type: (str, float, float) -> None
"""Send a GaugeDelta metric to change a Gauge by the specified value"""
if self._should_send_metric(name, rate):
if not is_numeric(delta):
delta = float(delta)
self._request(
... |
def set(self, name, value, rate=1):
# type: (str, str, float) -> None
"""Send a Set metric with the specified unique value"""
if self._should_send_metric(name, rate):
value = str(value)
self._request(
Set(
self._create_metric_name_for_... |
def _request(self, data):
# type: (str) -> None
"""Override parent by buffering the metric instead of sending now"""
data = bytearray("{}\n".format(data).encode())
self._prepare_batches_for_storage(len(data))
self._batches[-1].extend(data) |
def batch_client(self, size=512):
# type: (int) -> BatchClient
"""Return a batch client with same settings of the client"""
batch_client = BatchClient(self.host, self.port, self.prefix, size)
self._configure_client(batch_client)
return batch_client |
def unit_client(self):
# type: () -> Client
"""Return a client with same settings of the batch client"""
client = Client(self.host, self.port, self.prefix)
self._configure_client(client)
return client |
def flush(self):
# type: () -> BatchClient
"""Send buffered metrics in batch requests"""
address = self.remote_address
while len(self._batches) > 0:
self._socket.sendto(self._batches[0], address)
self._batches.popleft()
return self |
def my_permission_factory(record, *args, **kwargs):
"""My permission factory."""
def can(self):
rec = Record.get_record(record.id)
return rec.get('access', '') == 'open'
return type('MyPermissionChecker', (), {'can': can})() |
def batch_client(self, size=512):
# type: (int) -> TCPBatchClient
"""Return a TCP batch client with same settings of the TCP client"""
batch_client = TCPBatchClient(self.host, self.port, self.prefix, size)
self._configure_client(batch_client)
return batch_client |
def flush(self):
"""Send buffered metrics in batch requests over TCP"""
# type: () -> TCPBatchClient
while len(self._batches) > 0:
self._socket.sendall(self._batches[0])
self._batches.popleft()
return self |
def unit_client(self):
# type: () -> TCPClient
"""Return a TCPClient with same settings of the batch TCP client"""
client = TCPClient(self.host, self.port, self.prefix)
self._configure_client(client)
return client |
def weighted_choice(choices):
"""
Supposes that choices is sequence of two elements items,
where first one is the probability and second is the
result object or callable
>>> result = weighted_choice([(20,'x'), (100, 'y')])
>>> result in ['x', 'y']
True
"""
total = sum([wei... |
def any_float(min_value=0, max_value=100, precision=2):
"""
Returns random float
>>> result = any_float(min_value=0, max_value=100, precision=2)
>>> type(result)
<type 'float'>
>>> result >=0 and result <= 100
True
"""
return round(random.uniform(min_value, max_value... |
def any_string(letters = ascii_letters, min_length=3, max_length=100):
"""
Return string with random content
>>> result = any_string(letters = ascii_letters, min_length=3, max_length=100)
>>> type(result)
<type 'str'>
>>> len(result) in range(3,101)
True
>>> any([c in ascii_let... |
def any_date(from_date=date(1990, 1, 1), to_date=date.today()):
"""
Return random date from the [from_date, to_date] interval
>>> result = any_date(from_date=date(1990,1,1), to_date=date(1990,1,3))
>>> type(result)
<type 'datetime.date'>
>>> result >= date(1990,1,1) and result <= date(19... |
def any_datetime(from_date=datetime(1990, 1, 1), to_date=datetime.now()):
"""
Return random datetime from the [from_date, to_date] interval
>>> result = any_datetime(from_date=datetime(1990,1,1), to_date=datetime(1990,1,3))
>>> type(result)
<type 'datetime.datetime'>
>>> result >= dateti... |
def any_decimal(min_value=Decimal(0), max_value=Decimal('99.99'), decimal_places=2):
"""
Return random decimal from the [min_value, max_value] interval
>>> result = any_decimal(min_value=0.999, max_value=3, decimal_places=3)
>>> type(result)
<class 'decimal.Decimal'>
>>> result >= Decima... |
def any_user(password=None, permissions=[], groups=[], **kwargs):
"""
Shortcut for creating Users
Permissions could be a list of permission names
If not specified, creates active, non superuser
and non staff user
"""
is_active = kwargs.pop('is_active', True)
is_superuser = kwargs.pop... |
def interpretAsOpenMath(x):
"""tries to convert a Python object into an OpenMath object
this is not a replacement for using a Converter for exporting Python objects
instead, it is used conveniently building OM objects in DSL embedded in Python
inparticular, it converts Python functions into OMBinding ob... |
def convertAsOpenMath(term, converter):
""" Converts a term into OpenMath, using either a converter or the interpretAsOpenMath method """
# if we already have openmath, or have some of our magic helpers, use interpretAsOpenMath
if hasattr(term, "_ishelper") and term._ishelper or isinstance(term, om.OMA... |
def to_python(self, omobj):
""" Convert OpenMath object to Python """
# general overrides
if omobj.__class__ in self._omclass_to_py:
return self._omclass_to_py[omobj.__class__](omobj)
# oms
elif isinstance(omobj, om.OMSymbol):
return self._lookup_to_python... |
def to_openmath(self, obj):
""" Convert Python object to OpenMath """
for cl, conv in reversed(self._conv_to_om):
if cl is None or isinstance(obj, cl):
try:
return conv(obj)
except CannotConvertError:
continue
i... |
def register_to_openmath(self, py_class, converter):
"""Register a conversion from Python to OpenMath
:param py_class: A Python class the conversion is attached to, or None
:type py_class: None, type
:param converter: A conversion function or an OpenMath object
:type converter:... |
def _deprecated_register_to_python(self, cd, name, converter=None):
"""Register a conversion from OpenMath to Python
This function has two forms. A three-arguments one:
:param cd: A content dictionary name
:type cd: str
:param name: A symbol name
:type name: str
... |
def _deprecated_register(self, py_class, to_om, om_cd, om_name, to_py=None):
"""
This is a shorthand for:
``self.register_to_python(om_cd, om_name, to_py)``
``self.register_to_openmath(py_class, to_om)``
"""
self.register_to_python(om_cd, om_name, to_py)
se... |
def init_app(self, app):
"""
Used to initialize redis with app object
"""
app.config.setdefault('REDIS_URLS', {
'main': 'redis://localhost:6379/0',
'admin': 'redis://localhost:6379/1',
})
app.before_request(self.before_request)
self.app ... |
def valid_choices(choices):
"""
Return list of choices's keys
"""
for key, value in choices:
if isinstance(value, (list, tuple)):
for key, _ in value:
yield key
else:
yield key |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.