_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q261900
Deposit._publish_edited
validation
def _publish_edited(self): """Publish the deposit after for editing.""" record_pid, record = self.fetch_published() if record.revision_id == self['_deposit']['pid']['revision_id']: data = dict(self.dumps()) else:
python
{ "resource": "" }
q261901
Deposit.publish
validation
def publish(self, pid=None, id_=None): """Publish a deposit. If it's the first time: * it calls the minter and set the following meta information inside the deposit: .. code-block:: python deposit['_deposit'] = { 'type': pid_type, 'value': pid_value, 'revision_id': 0, } * A dump of all information inside the deposit is done. * A snapshot of the files is done. Otherwise, published the new edited version. In this case, if in the mainwhile someone already published a new version, it'll try to merge the changes with the latest version. .. note:: no need for indexing as it calls `self.commit()`. Status required: ``'draft'``. :param pid: Force
python
{ "resource": "" }
q261902
Deposit._prepare_edit
validation
def _prepare_edit(self, record): """Update selected keys. :param record: The record to prepare. """ data = record.dumps() # Keep current record revision for merging.
python
{ "resource": "" }
q261903
Deposit.edit
validation
def edit(self, pid=None): """Edit deposit. #. The signal :data:`invenio_records.signals.before_record_update` is sent before the edit execution. #. The following meta information are saved inside the deposit: .. code-block:: python deposit['_deposit']['pid'] = record.revision_id deposit['_deposit']['status'] = 'draft' deposit['$schema'] = deposit_schema_from_record_schema #. The signal :data:`invenio_records.signals.after_record_update` is sent after the edit execution. #. The deposit index is updated. Status required: `published`. .. note:: the process fails if the pid has status :attr:`invenio_pidstore.models.PIDStatus.REGISTERED`. :param pid: Force a pid object. (Default: ``None``) :returns: A new Deposit object. """ pid = pid or self.pid with db.session.begin_nested(): before_record_update.send( current_app._get_current_object(), record=self)
python
{ "resource": "" }
q261904
Deposit.discard
validation
def discard(self, pid=None): """Discard deposit changes. #. The signal :data:`invenio_records.signals.before_record_update` is sent before the edit execution. #. It restores the last published version. #. The following meta information are saved inside the deposit: .. code-block:: python deposit['$schema'] = deposit_schema_from_record_schema #. The signal :data:`invenio_records.signals.after_record_update` is sent after the edit execution.
python
{ "resource": "" }
q261905
Deposit.delete
validation
def delete(self, force=True, pid=None): """Delete deposit. Status required: ``'draft'``. :param force: Force deposit delete. (Default: ``True``) :param pid: Force pid object. (Default: ``None``) :returns: A new Deposit object. """ pid
python
{ "resource": "" }
q261906
Deposit.clear
validation
def clear(self, *args, **kwargs): """Clear only drafts. Status required: ``'draft'``.
python
{ "resource": "" }
q261907
Deposit.update
validation
def update(self, *args, **kwargs): """Update only drafts. Status required: ``'draft'``.
python
{ "resource": "" }
q261908
Deposit.patch
validation
def patch(self, *args, **kwargs): """Patch only drafts. Status required: ``'draft'``.
python
{ "resource": "" }
q261909
Deposit.files
validation
def files(self): """List of Files inside the deposit. Add validation on ``sort_by`` method: if, at the time of files access, the record is not a ``'draft'`` then a :exc:`invenio_pidstore.errors.PIDInvalidAction` is rised. """ files_ = super(Deposit, self).files if files_: sort_by_ = files_.sort_by def sort_by(*args, **kwargs):
python
{ "resource": "" }
q261910
rst2node
validation
def rst2node(doc_name, data): """Converts a reStructuredText into its node """ if not data: return parser = docutils.parsers.rst.Parser() document = docutils.utils.new_document('<%s>' % doc_name) document.settings = docutils.frontend.OptionParser().get_default_values()
python
{ "resource": "" }
q261911
setup
validation
def setup(app): """Hook the directives when Sphinx ask for it.""" if 'http' not in app.domains:
python
{ "resource": "" }
q261912
api._parse_response
validation
def _parse_response(self, response): """Parses the API response and raises appropriate errors if raise_errors was set to True """ if not self._raise_errors: return response is_4xx_error = str(response.status_code)[0] == '4' is_5xx_error = str(response.status_code)[0] == '5' content = response.content if
python
{ "resource": "" }
q261913
api.templates
validation
def templates(self, timeout=None): """ API call to get a list of templates """ return self._api_request(
python
{ "resource": "" }
q261914
api.get_template
validation
def get_template(self, template_id, version=None, timeout=None): """ API call to get a specific template """ if (version): return self._api_request( self.TEMPLATES_VERSION_ENDPOINT % (template_id, version),
python
{ "resource": "" }
q261915
api.create_template
validation
def create_template( self, name, subject, html, text='', timeout=None ): """ API call to create a template """ payload = { 'name': name, 'subject': subject, 'html': html, 'text': text }
python
{ "resource": "" }
q261916
api.create_new_locale
validation
def create_new_locale( self, template_id, locale, version_name, subject, text='', html='', timeout=None ): """ API call to create a new locale and version of a template """ payload = { 'locale': locale, 'name': version_name, 'subject': subject } if html:
python
{ "resource": "" }
q261917
api.create_new_version
validation
def create_new_version( self, name, subject, text='', template_id=None, html=None, locale=None, timeout=None ): """ API call to create a new version of a template """ if(html): payload = { 'name': name, 'subject': subject, 'html': html, 'text': text } else: payload = { 'name': name, 'subject': subject, 'text': text } if locale: url = self.TEMPLATES_SPECIFIC_LOCALE_VERSIONS_ENDPOINT
python
{ "resource": "" }
q261918
api.update_template_version
validation
def update_template_version( self, name, subject, template_id, version_id, text='', html=None, timeout=None ): """ API call to update a template version """ if(html): payload = { 'name': name,
python
{ "resource": "" }
q261919
api.snippets
validation
def snippets(self, timeout=None): """ API call to get list of snippets """ return self._api_request(
python
{ "resource": "" }
q261920
api.get_snippet
validation
def get_snippet(self, snippet_id, timeout=None): """ API call to get a specific Snippet """ return self._api_request(
python
{ "resource": "" }
q261921
api.create_snippet
validation
def create_snippet(self, name, body, timeout=None): """ API call to create a Snippet """ payload = { 'name': name, 'body': body } return self._api_request(
python
{ "resource": "" }
q261922
api._make_file_dict
validation
def _make_file_dict(self, f): """Make a dictionary with filename and base64 file data""" if isinstance(f, dict): file_obj = f['file'] if 'filename' in f: file_name = f['filename'] else: file_name = file_obj.name else: file_obj = f file_name = f.name
python
{ "resource": "" }
q261923
api.send
validation
def send( self, email_id, recipient, email_data=None, sender=None, cc=None, bcc=None, tags=[], headers={}, esp_account=None, locale=None, email_version_name=None, inline=None, files=[], timeout=None ): """ API call to send an email """ if not email_data: email_data = {} # for backwards compatibility, will be removed if isinstance(recipient, string_types): warnings.warn( "Passing email directly for recipient is deprecated", DeprecationWarning) recipient = {'address': recipient} payload = { 'email_id': email_id, 'recipient': recipient, 'email_data': email_data } if sender: payload['sender'] = sender if cc: if not type(cc) == list: logger.error( 'kwarg cc must be type(list), got %s' % type(cc)) payload['cc'] = cc if bcc: if not type(bcc) == list: logger.error( 'kwarg bcc must be type(list), got %s' % type(bcc)) payload['bcc'] = bcc if tags: if not type(tags) == list: logger.error( 'kwarg tags must be type(list), got %s' % (type(tags))) payload['tags'] = tags if headers: if not type(headers) == dict: logger.error( 'kwarg headers must be type(dict), got %s' % ( type(headers) ) ) payload['headers'] = headers if esp_account:
python
{ "resource": "" }
q261924
BatchAPI.execute
validation
def execute(self, timeout=None): """Execute all currently queued batch commands""" logger.debug(' > Batch API request (length %s)' % len(self._commands)) auth = self._build_http_auth() headers = self._build_request_headers() logger.debug('\tbatch headers: %s' % headers) logger.debug('\tbatch command length: %s' % len(self._commands)) path = self._build_request_path(self.BATCH_ENDPOINT) data = json.dumps(self._commands, cls=self._json_encoder) r = requests.post( path, auth=auth,
python
{ "resource": "" }
q261925
TabView.get_group_tabs
validation
def get_group_tabs(self): """ Return instances of all other tabs that are members of the tab's tab group. """ if self.tab_group is None: raise ImproperlyConfigured( "%s requires a definition of 'tab_group'" %
python
{ "resource": "" }
q261926
TabView._process_tabs
validation
def _process_tabs(self, tabs, current_tab, group_current_tab): """ Process and prepare tabs. This includes steps like updating references to the current tab, filtering out hidden tabs, sorting tabs etc... Args: tabs: The list of tabs to process. current_tab: The reference to the currently loaded tab. group_current_tab: The reference to the active tab in the current tab group. For parent tabs, this is different than for the current tab group. Returns:
python
{ "resource": "" }
q261927
TabView.get_context_data
validation
def get_context_data(self, **kwargs): """ Adds tab information to context. To retrieve a list of all group tab instances, use ``{{ tabs }}`` in your template. The id of the current tab is added as ``current_tab_id`` to the template context. If the current tab has a parent tab the parent's id is added to the template context as ``parent_tab_id``. Instances of all tabs of the parent level are added as ``parent_tabs`` to the context. If the current tab has children they are added to the template context as ``child_tabs``. """ context = super(TabView, self).get_context_data(**kwargs) # Update the context with kwargs, TemplateView doesn't do this. context.update(kwargs) # Add tabs and "current" references to context process_tabs_kwargs = { 'tabs': self.get_group_tabs(), 'current_tab': self, 'group_current_tab': self, } context['tabs'] = self._process_tabs(**process_tabs_kwargs) context['current_tab_id'] = self.tab_id # Handle parent tabs if self.tab_parent is not None: # Verify that tab parent is valid if self.tab_parent not in self._registry: msg = '%s has no attribute _is_tab' %
python
{ "resource": "" }
q261928
normalize_name
validation
def normalize_name(s): """Convert a string into a valid python attribute name. This function is called to convert ASCII strings to something that can pass as python attribute name, to be used with namedtuples. >>> str(normalize_name('class')) 'class_' >>> str(normalize_name('a-name')) 'a_name' >>> str(normalize_name('a n\u00e4me')) 'a_name' >>> str(normalize_name('Name')) 'Name' >>> str(normalize_name('')) '_'
python
{ "resource": "" }
q261929
schema
validation
def schema(tg): """ Convert the table and column descriptions of a `TableGroup` into specifications for the DB schema. :param ds: :return: A pair (tables, reference_tables). """ tables = {} for tname, table in tg.tabledict.items(): t = TableSpec.from_table_metadata(table) tables[t.name] = t for at in t.many_to_many.values(): tables[at.name] = at # We must determine the order in which tables must be created! ordered = OrderedDict() i = 0 # We loop through the tables repeatedly, and whenever we find one, which has all # referenced tables already in ordered, we move it from tables to ordered. while tables and i < 100: i +=
python
{ "resource": "" }
q261930
Database.write
validation
def write(self, _force=False, _exists_ok=False, **items): """ Creates a db file with the core schema. :param force: If `True` an existing db file will be overwritten. """ if self.fname and self.fname.exists(): raise ValueError('db file already exists, use force=True to overwrite') with self.connection() as db: for table in self.tables: db.execute(table.sql(translate=self.translate)) db.execute('PRAGMA foreign_keys = ON;') db.commit() refs = defaultdict(list) # collects rows in association tables. for t in self.tables: if t.name not in items: continue rows, keys = [], [] cols = {c.name: c for c in t.columns} for i, row in enumerate(items[t.name]): pk = row[t.primary_key[0]] \ if t.primary_key and len(t.primary_key) == 1 else None values = [] for k, v in row.items(): if k in t.many_to_many: assert pk at = t.many_to_many[k] atkey = tuple([at.name] + [c.name for c in at.columns]) for vv in v: fkey, context = self.association_table_context(t, k, vv)
python
{ "resource": "" }
q261931
iterrows
validation
def iterrows(lines_or_file, namedtuples=False, dicts=False, encoding='utf-8', **kw): """Convenience factory function for csv reader. :param lines_or_file: Content to be read. Either a file handle, a file path or a list\ of strings. :param namedtuples: Yield namedtuples. :param dicts: Yield dicts. :param encoding: Encoding of the content.
python
{ "resource": "" }
q261932
rewrite
validation
def rewrite(fname, visitor, **kw): """Utility function to rewrite rows in tsv files. :param fname: Path of the dsv file to operate on. :param visitor: A callable that takes a line-number and a row as input and returns a \ (modified) row or None to filter out the row. :param kw: Keyword parameters are passed through to csv.reader/csv.writer. """
python
{ "resource": "" }
q261933
filter_rows_as_dict
validation
def filter_rows_as_dict(fname, filter_, **kw): """Rewrite a dsv file, filtering the rows. :param fname: Path to dsv file :param filter_: callable which accepts a `dict` with a row's data as single argument\ returning a `Boolean`
python
{ "resource": "" }
q261934
dump_grid
validation
def dump_grid(grid): """ Dump a single grid to its ZINC representation. """ header = 'ver:%s' % dump_str(str(grid._version), version=grid._version) if bool(grid.metadata): header += ' '
python
{ "resource": "" }
q261935
parse
validation
def parse(grid_str, mode=MODE_ZINC, charset='utf-8'): ''' Parse the given Zinc text and return the equivalent data. ''' # Decode incoming text (or python3 will whine!) if isinstance(grid_str, six.binary_type): grid_str = grid_str.decode(encoding=charset) # Split the separate grids up, the grammar definition has trouble splitting # them up normally. This will truncate the newline off the end of the last # row. _parse = functools.partial(parse_grid, mode=mode, charset=charset) if mode == MODE_JSON: if isinstance(grid_str, six.string_types):
python
{ "resource": "" }
q261936
MetadataObject.append
validation
def append(self, key, value=MARKER, replace=True): ''' Append the item to the metadata. '''
python
{ "resource": "" }
q261937
MetadataObject.extend
validation
def extend(self, items, replace=True): ''' Append the items to the metadata. ''' if isinstance(items, dict) or isinstance(items, SortableDict): items =
python
{ "resource": "" }
q261938
Shape.regular_polygon
validation
def regular_polygon(cls, center, radius, n_vertices, start_angle=0, **kwargs): """Construct a regular polygon. Parameters ---------- center : array-like radius : float n_vertices : int start_angle : float, optional
python
{ "resource": "" }
q261939
Shape.circle
validation
def circle(cls, center, radius, n_vertices=50, **kwargs): """Construct a circle. Parameters ---------- center : array-like radius : float n_vertices : int, optional Number of points to draw. Decrease for performance, increase
python
{ "resource": "" }
q261940
Shape.rectangle
validation
def rectangle(cls, vertices, **kwargs): """Shortcut for creating a rectangle aligned with the screen axes from only two corners. Parameters ---------- vertices : array-like An array containing the ``[x, y]`` positions of two corners. kwargs Other keyword arguments are passed to the |Shape| constructor.
python
{ "resource": "" }
q261941
Shape.from_dict
validation
def from_dict(cls, spec): """Create a |Shape| from a dictionary specification. Parameters ---------- spec : dict A dictionary with either the fields ``'center'`` and ``'radius'`` (for a circle), ``'center'``, ``'radius'``, and ``'n_vertices'`` (for a regular polygon), or ``'vertices'``. If only two vertices are given, they are assumed to be lower left and top right corners of a rectangle. Other fields are interpreted as keyword arguments. """ spec = spec.copy()
python
{ "resource": "" }
q261942
Shape._kwargs
validation
def _kwargs(self): """Keyword arguments for recreating the Shape from the vertices. """
python
{ "resource": "" }
q261943
Shape.rotate
validation
def rotate(self, angle, center=None): """Rotate the shape, in-place. Parameters ---------- angle : float Angle to rotate, in radians counter-clockwise. center : array-like, optional Point about which to rotate.
python
{ "resource": "" }
q261944
Shape.flip_x
validation
def flip_x(self, center=None): """Flip the shape in the x direction, in-place. Parameters ---------- center : array-like, optional Point about which to flip. If not passed, the center of the
python
{ "resource": "" }
q261945
Shape.flip_y
validation
def flip_y(self, center=None): """Flip the shape in the y direction, in-place. Parameters ---------- center : array-like, optional Point about which to flip. If not passed, the center of the
python
{ "resource": "" }
q261946
Shape.flip
validation
def flip(self, angle, center=None): """ Flip the shape in an arbitrary direction. Parameters ---------- angle : array-like The angle, in radians counter-clockwise from the horizontal axis, defining the angle about which to flip the shape (of a line through `center`). center :
python
{ "resource": "" }
q261947
Shape.draw
validation
def draw(self): """Draw the shape in the current OpenGL context. """ if self.enabled: self._vertex_list.colors = self._gl_colors
python
{ "resource": "" }
q261948
Shape.update
validation
def update(self, dt): """Update the shape's position by moving it forward according to its velocity. Parameters ---------- dt : float
python
{ "resource": "" }
q261949
_map_timezones
validation
def _map_timezones(): """ Map the official Haystack timezone list to those recognised by pytz. """ tz_map = {} todo = HAYSTACK_TIMEZONES_SET.copy() for full_tz in pytz.all_timezones: # Finished case: if not bool(todo): # pragma: no cover # This is nearly impossible for us to cover, and an unlikely case. break # Case 1: exact match if full_tz in todo: tz_map[full_tz] = full_tz # Exact match todo.discard(full_tz) continue
python
{ "resource": "" }
q261950
timezone
validation
def timezone(haystack_tz, version=LATEST_VER): """ Retrieve the Haystack timezone """ tz_map = get_tz_map(version=version)
python
{ "resource": "" }
q261951
_unescape
validation
def _unescape(s, uri=False): """ Iterative parser for string escapes. """ out = '' while len(s) > 0: c = s[0] if c == '\\': # Backslash escape esc_c = s[1] if esc_c in ('u', 'U'): # Unicode escape out += six.unichr(int(s[2:6], base=16)) s = s[6:] continue else: if esc_c == 'b': out += '\b' elif esc_c == 'f': out += '\f' elif esc_c == 'n': out += '\n' elif esc_c == 'r':
python
{ "resource": "" }
q261952
parse_grid
validation
def parse_grid(grid_data): """ Parse the incoming grid. """ try: # Split the grid up. grid_parts = NEWLINE_RE.split(grid_data) if len(grid_parts) < 2: raise ZincParseException('Malformed grid received', grid_data, 1, 1) # Grid and column metadata are the first two lines. grid_meta_str = grid_parts.pop(0) col_meta_str = grid_parts.pop(0) # First element is the grid metadata ver_match = VERSION_RE.match(grid_meta_str) if ver_match is None: raise ZincParseException( 'Could not determine version from %r' % grid_meta_str, grid_data, 1, 1) version = Version(ver_match.group(1)) # Now parse the rest of the grid accordingly try: grid_meta = hs_gridMeta[version].parseString(grid_meta_str, parseAll=True)[0] except pp.ParseException as pe: # Raise a new exception with the appropriate line number. raise ZincParseException( 'Failed to parse grid metadata: %s' % pe, grid_data, 1, pe.col) except: # pragma: no cover # Report an error to the log if we fail to parse something. LOG.debug('Failed to parse grid meta: %r', grid_meta_str) raise try: col_meta = hs_cols[version].parseString(col_meta_str, parseAll=True)[0] except pp.ParseException as pe: # Raise a new exception with the appropriate line number. raise ZincParseException( 'Failed to parse column metadata: %s' \ % reformat_exception(pe, 2), grid_data, 2, pe.col) except: # pragma: no cover # Report an error to the log if we fail to parse something. LOG.debug('Failed to parse column meta: %r', col_meta_str) raise row_grammar = hs_row[version] def _parse_row(row_num_and_data):
python
{ "resource": "" }
q261953
parse_scalar
validation
def parse_scalar(scalar_data, version): """ Parse a Project Haystack scalar in ZINC format. """ try: return hs_scalar[version].parseString(scalar_data, parseAll=True)[0] except pp.ParseException as pe: # Raise a new exception with the appropriate line number. raise ZincParseException(
python
{ "resource": "" }
q261954
SortableDict.add_item
validation
def add_item(self, key, value, after=False, index=None, pos_key=None, replace=True): """ Add an item at a specific location, possibly replacing the existing item. If after is True, we insert *after* the given index, otherwise we insert before. The position is specified using either index or pos_key, the former specifies the position from the start of the array (base 0). pos_key specifies the name of another key, and positions the new key relative to that key. When replacing, the position will be left un-changed unless a location is specified explicitly. """ if self._validate_fn: self._validate_fn(value) if (index is not None) and (pos_key is not None): raise ValueError('Either specify index or pos_key, not both.') elif pos_key is not None: try: index = self.index(pos_key) except ValueError: raise KeyError('%r not found' % pos_key) if after and (index
python
{ "resource": "" }
q261955
dump
validation
def dump(grids, mode=MODE_ZINC): """ Dump the given grids in the specified over-the-wire format. """ if isinstance(grids, Grid): return dump_grid(grids, mode=mode) _dump = functools.partial(dump_grid,
python
{ "resource": "" }
q261956
Grid._detect_or_validate
validation
def _detect_or_validate(self, val): ''' Detect the version used from the row content, or validate against the version if given. ''' if isinstance(val, list) \ or isinstance(val, dict) \
python
{ "resource": "" }
q261957
Grid._assert_version
validation
def _assert_version(self, version): ''' Assert that the grid version is equal to or above the given value. If no version is set, set the version. ''' if self.nearest_version < version: if self._version_given:
python
{ "resource": "" }
q261958
Version.nearest
validation
def nearest(self, ver): """ Retrieve the official version nearest the one given. """ if not isinstance(ver, Version): ver = Version(ver) if ver in OFFICIAL_VERSIONS: return ver # We might not have an exact match for that. # See if we have one that's newer than the grid we're looking at. versions = list(OFFICIAL_VERSIONS) versions.sort(reverse=True) best = None for candidate in versions: # Due to ambiguities, we might have an exact match and not know it. # '2.0' will not hash to the same value as '2.0.0', but both are # equivalent. if candidate == ver: # We can't beat this, make a note of the match for later return candidate # If we have not seen a better candidate, and this is older # then we may have to settle for that. if (best is None) and (candidate < ver): warnings.warn('This version of hszinc does not yet '\
python
{ "resource": "" }
q261959
encrypt_files
validation
def encrypt_files(selected_host, only_link, file_name): """ Encrypts file with gpg and random generated password """ if ENCRYPTION_DISABLED: print('For encryption please install gpg') exit() passphrase = '%030x' % random.randrange(16**30) source_filename = file_name cmd = 'gpg --batch --symmetric --cipher-algo AES256 --passphrase-fd 0 ' \ '--output - {}'.format(source_filename)
python
{ "resource": "" }
q261960
check_max_filesize
validation
def check_max_filesize(chosen_file, max_size): """ Checks file sizes for host """
python
{ "resource": "" }
q261961
parse_arguments
validation
def parse_arguments(args, clone_list): """ Makes parsing arguments a function. """ returned_string="" host_number = args.host if args.show_list: print(generate_host_string(clone_list, "Available hosts: ")) exit() if args.decrypt: for i in args.files: print(decrypt_files(i)) exit() if args.files: for i in args.files: if args.limit_size: if args.host == host_number and host_number is not None: if not check_max_filesize(i, clone_list[host_number][3]): host_number = None for n, host in enumerate(clone_list): if not check_max_filesize(i, host[3]): clone_list[n] = None if not clone_list: print('None of the clones is able to support so big file.') if args.no_cloudflare: if args.host == host_number and host_number is not None and not clone_list[host_number][4]: print("This host uses Cloudflare, please choose different host.") exit(1) else: for n, host in enumerate(clone_list): if not host[4]: clone_list[n] = None clone_list = list(filter(None, clone_list)) if host_number is None or args.host != host_number: host_number = random.randrange(0, len(clone_list)) while True: try: if args.encrypt: returned_string = encrypt_files(clone_list[host_number], args.only_link, i) else: returned_string = upload_files(open(i, 'rb'), \ clone_list[host_number], args.only_link, i)
python
{ "resource": "" }
q261962
upload_files
validation
def upload_files(selected_file, selected_host, only_link, file_name): """ Uploads selected file to the host, thanks to the fact that every pomf.se based site has pretty much the same architecture. """ try: answer = requests.post( url=selected_host[0]+"upload.php", files={'files[]':selected_file}) file_name_1 = re.findall(r'"url": *"((h.+\/){0,1}(.+?))"[,\}]', \ answer.text.replace("\\", ""))[0][2] if
python
{ "resource": "" }
q261963
decrypt_files
validation
def decrypt_files(file_link): """ Decrypts file from entered links """ if ENCRYPTION_DISABLED: print('For decryption please install gpg') exit() try: parsed_link = re.findall(r'(.*/(.*))#(.{30})', file_link)[0] req = urllib.request.Request( parsed_link[0], data=None, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) ' \ ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) #downloads the file using fake useragent file_response = urllib.request.urlopen(req) file_to_decrypt = file_response.read() #decrypts the data using piping to ggp decrypt_r, decrypt_w = os.pipe()
python
{ "resource": "" }
q261964
DefinitionHandler.from_schema
validation
def from_schema(self, schema_node, base_name=None): """ Creates a Swagger definition from a colander schema. :param schema_node: Colander schema to be transformed into a Swagger definition. :param base_name: Schema alternative title.
python
{ "resource": "" }
q261965
ParameterHandler.from_schema
validation
def from_schema(self, schema_node): """ Creates a list of Swagger params from a colander request schema. :param schema_node: Request schema to be transformed into Swagger. :param validators: Validators used in colander with the schema. :rtype: list :returns: List of Swagger parameters. """ params = [] for param_schema in schema_node.children: location = param_schema.name if location is 'body': name = param_schema.__class__.__name__ if name == 'body': name = schema_node.__class__.__name__ + 'Body' param = self.parameter_converter(location, param_schema) param['name']
python
{ "resource": "" }
q261966
ParameterHandler.from_path
validation
def from_path(self, path): """ Create a list of Swagger path params from a cornice service path. :type path: string :rtype: list """ path_components = path.split('/') param_names = [comp[1:-1] for comp in path_components
python
{ "resource": "" }
q261967
ParameterHandler._ref
validation
def _ref(self, param, base_name=None): """ Store a parameter schema and return a reference to it. :param schema: Swagger parameter definition. :param base_name: Name that should be used for the reference. :rtype: dict :returns: JSON pointer to the original parameter definition.
python
{ "resource": "" }
q261968
ResponseHandler.from_schema_mapping
validation
def from_schema_mapping(self, schema_mapping): """ Creates a Swagger response object from a dict of response schemas. :param schema_mapping: Dict with entries matching ``{status_code: response_schema}``. :rtype: dict :returns: Response schema. """ responses = {} for status, response_schema in schema_mapping.items(): response = {} if response_schema.description: response['description'] = response_schema.description else: raise CorniceSwaggerException('Responses must have a description.') for field_schema in response_schema.children: location = field_schema.name if location == 'body': title = field_schema.__class__.__name__ if title == 'body': title = response_schema.__class__.__name__ + 'Body' field_schema.title = title
python
{ "resource": "" }
q261969
ResponseHandler._ref
validation
def _ref(self, resp, base_name=None): """ Store a response schema and return a reference to it. :param schema: Swagger response definition. :param base_name: Name that should be used for the reference. :rtype: dict :returns: JSON pointer to the original response definition.
python
{ "resource": "" }
q261970
CorniceSwagger.generate
validation
def generate(self, title=None, version=None, base_path=None, info=None, swagger=None, **kwargs): """Generate a Swagger 2.0 documentation. Keyword arguments may be used to provide additional information to build methods as such ignores. :param title: The name presented on the swagger document. :param version: The version of the API presented on the swagger document. :param base_path: The path that all requests to the API must refer to. :param info: Swagger info field. :param swagger: Extra fields that should be provided on the swagger documentation. :rtype: dict :returns: Full OpenAPI/Swagger compliant specification for the application. """ title = title or self.api_title version = version or self.api_version info = info or self.swagger.get('info', {}) swagger = swagger or self.swagger base_path = base_path or self.base_path swagger = swagger.copy() info.update(title=title, version=version) swagger.update(swagger='2.0', info=info, basePath=base_path) paths, tags = self._build_paths() # Update the provided tags with the extracted ones preserving order if tags: swagger.setdefault('tags', []) tag_names = {t['name'] for t in swagger['tags']}
python
{ "resource": "" }
q261971
CorniceSwagger._build_paths
validation
def _build_paths(self): """ Build the Swagger "paths" and "tags" attributes from cornice service definitions. """ paths = {} tags = [] for service in self.services: path, path_obj = self._extract_path_from_service(service) service_tags = getattr(service, 'tags', []) self._check_tags(service_tags) tags = self._get_tags(tags, service_tags) for method, view, args in service.definitions: if method.lower() in map(str.lower, self.ignore_methods): continue op = self._extract_operation_from_view(view, args) if any(ctype in op.get('consumes', []) for ctype in self.ignore_ctypes): continue # XXX: Swagger doesn't support different schemas for for a same method # with different ctypes as cornice. If this happens, you may ignore one # content-type from the documentation otherwise we raise an Exception # Related to https://github.com/OAI/OpenAPI-Specification/issues/146 previous_definition = path_obj.get(method.lower()) if previous_definition: raise CorniceSwaggerException(("Swagger doesn't support multiple " "views for a same method. You may " "ignore one.")) # If tag not defined and a default tag is provided if 'tags' not in op and self.default_tags: if callable(self.default_tags): op['tags'] = self.default_tags(service, method) else: op['tags'] = self.default_tags op_tags = op.get('tags', [])
python
{ "resource": "" }
q261972
CorniceSwagger._extract_path_from_service
validation
def _extract_path_from_service(self, service): """ Extract path object and its parameters from service definitions. :param service: Cornice service to extract information from. :rtype: dict :returns: Path definition. """ path_obj = {} path = service.path route_name = getattr(service, 'pyramid_route', None) # handle services that don't create fresh routes, # we still need the paths so we need to grab pyramid introspector to # extract that information if route_name: # avoid failure if someone forgets to pass registry registry = self.pyramid_registry or get_current_registry() route_intr = registry.introspector.get('routes', route_name) if route_intr: path = route_intr['pattern'] else: msg = 'Route `{}` is not found by ' \ 'pyramid introspector'.format(route_name)
python
{ "resource": "" }
q261973
CorniceSwagger._extract_operation_from_view
validation
def _extract_operation_from_view(self, view, args): """ Extract swagger operation details from colander view definitions. :param view: View to extract information from. :param args: Arguments from the view decorator. :rtype: dict :returns: Operation definition. """ op = { 'responses': { 'default': { 'description': 'UNDOCUMENTED RESPONSE' } }, } # If 'produces' are not defined in the view, try get from renderers renderer = args.get('renderer', '') if "json" in renderer: # allows for "json" or "simplejson" produces = ['application/json'] elif renderer == 'xml': produces = ['text/xml'] else: produces = None if produces: op.setdefault('produces', produces) # Get explicit accepted content-types consumes = args.get('content_type') if consumes is not None: # convert to a list, if it's not yet one
python
{ "resource": "" }
q261974
CorniceSwagger._extract_transform_colander_schema
validation
def _extract_transform_colander_schema(self, args): """ Extract schema from view args and transform it using the pipeline of schema transformers :param args: Arguments from the view decorator. :rtype: colander.MappingSchema() :returns: View schema cloned and transformed """ schema = args.get('schema', colander.MappingSchema())
python
{ "resource": "" }
q261975
ParameterConverter.convert
validation
def convert(self, schema_node, definition_handler): """ Convert node schema into a parameter object. """ converted = { 'name': schema_node.name, 'in': self._in, 'required': schema_node.required } if schema_node.description: converted['description'] = schema_node.description if schema_node.default:
python
{ "resource": "" }
q261976
merge_dicts
validation
def merge_dicts(base, changes): """Merge b into a recursively, without overwriting values. :param base: the dict that will be altered.
python
{ "resource": "" }
q261977
get_transition_viewset_method
validation
def get_transition_viewset_method(transition_name, **kwargs): ''' Create a viewset method for the provided `transition_name` ''' @detail_route(methods=['post'], **kwargs) def inner_func(self, request, pk=None, **kwargs): object = self.get_object() transition_method = getattr(object, transition_name) transition_method(by=self.request.user)
python
{ "resource": "" }
q261978
get_viewset_transition_action_mixin
validation
def get_viewset_transition_action_mixin(model, **kwargs): ''' Find all transitions defined on `model`, then create a corresponding viewset action method for each and apply it to `Mixin`. Finally, return `Mixin` ''' instance = model() class Mixin(object): save_after_transition = True transitions = instance.get_all_status_transitions() transition_names = set(x.name for x in
python
{ "resource": "" }
q261979
fresh_cookies
validation
def fresh_cookies(ctx, mold=''): """Refresh the project from the original cookiecutter template.""" mold = mold or "https://github.com/Springerle/py-generic-project.git" # TODO: URL from config tmpdir = os.path.join(tempfile.gettempdir(), "cc-upgrade-pygments-markdown-lexer") if os.path.isdir('.git'): # TODO: Ensure there are no local unstashed changes pass # Make a copy of the new mold version if os.path.isdir(tmpdir): shutil.rmtree(tmpdir) if os.path.exists(mold): shutil.copytree(mold, tmpdir, ignore=shutil.ignore_patterns( ".git", ".svn", "*~",
python
{ "resource": "" }
q261980
ci
validation
def ci(ctx): """Perform continuous integration tasks.""" opts = [''] # 'tox' makes no sense in Travis if os.environ.get('TRAVIS', '').lower() == 'true': opts += ['test.pytest']
python
{ "resource": "" }
q261981
py_hash
validation
def py_hash(key, num_buckets): """Generate a number in the range [0, num_buckets). Args: key (int): The key to hash. num_buckets (int): Number of buckets to use. Returns: The bucket number `key` computes to. Raises: ValueError: If `num_buckets` is not a positive number. """ b, j = -1, 0 if
python
{ "resource": "" }
q261982
setup
validation
def setup(app): """ Initializer for Sphinx extension API. See http://www.sphinx-doc.org/en/stable/extdev/index.html#dev-extensions. """ lexer = MarkdownLexer() for alias
python
{ "resource": "" }
q261983
MdStat.load
validation
def load(self): """Return a dict of stats.""" ret = {} # Read the mdstat file with open(self.get_path(), 'r') as f: # lines is a list of line (with \n) lines = f.readlines() # First line: get the personalities # The "Personalities" line tells you what RAID level the kernel currently supports. # This can be changed by either changing the raid modules or recompiling the kernel. # Possible personalities include: [raid0]
python
{ "resource": "" }
q261984
MdStat.get_personalities
validation
def get_personalities(self, line): """Return a list of personalities readed from
python
{ "resource": "" }
q261985
MdStat.get_arrays
validation
def get_arrays(self, lines, personalities=[]): """Return a dict of arrays.""" ret = {} i = 0 while i < len(lines): try: # First array line: get the md device md_device = self.get_md_device_name(lines[i]) except IndexError:
python
{ "resource": "" }
q261986
MdStat.get_md_device
validation
def get_md_device(self, line, personalities=[]): """Return a dict of md device define in the line.""" ret = {} splitted = split('\W+', line) # Raid status # Active or 'started'. An inactive array is usually faulty. # Stopped arrays aren't visible here. ret['status'] = splitted[1] if splitted[2] in personalities: # Raid type (ex: RAID5) ret['type'] = splitted[2] # Array's components
python
{ "resource": "" }
q261987
MdStat.get_md_status
validation
def get_md_status(self, line): """Return a dict of md status define in the line.""" ret = {} splitted = split('\W+', line) if len(splitted) < 7: ret['available'] = None ret['used'] = None ret['config'] = None else: # The final 2
python
{ "resource": "" }
q261988
MdStat.get_components
validation
def get_components(self, line, with_type=True): """Return a dict of components in the line. key: device name (ex: 'sdc1') value: device role number """ ret = {} # Ignore (F) (see test 08) line2 = reduce(lambda x, y: x + y, split('\(.+\)', line))
python
{ "resource": "" }
q261989
register_receivers
validation
def register_receivers(app, config): """Register signal receivers which send events.""" for event_name, event_config in config.items(): event_builders = [ obj_or_import_string(func) for func in event_config.get('event_builders', []) ]
python
{ "resource": "" }
q261990
InternalMailbox.set_scheduled
validation
def set_scheduled(self): """ Returns True if state was successfully changed from idle to scheduled. """ with self._idle_lock: if self._idle:
python
{ "resource": "" }
q261991
StatsQueryResource.post
validation
def post(self, **kwargs): """Get statistics.""" data = request.get_json(force=False) if data is None: data = {} result = {} for query_name, config in data.items(): if config is None or not isinstance(config, dict) \ or (set(config.keys()) != {'stat', 'params'} and set(config.keys()) != {'stat'}): raise InvalidRequestInputError( 'Invalid Input. It should be of the form ' '{ STATISTIC_NAME: { "stat": STAT_TYPE, ' '"params": STAT_PARAMS \}}' ) stat = config['stat'] params = config.get('params', {}) try: query_cfg = current_stats.queries[stat] except KeyError: raise UnknownQueryError(stat) permission = current_stats.permission_factory(stat, params) if permission is not None and not permission.can(): message = ('You do not have a permission to query the '
python
{ "resource": "" }
q261992
StatAggregator._get_oldest_event_timestamp
validation
def _get_oldest_event_timestamp(self): """Search for the oldest event timestamp.""" # Retrieve the oldest event in order to start aggregation # from there query_events = Search( using=self.client, index=self.event_index
python
{ "resource": "" }
q261993
StatAggregator.get_bookmark
validation
def get_bookmark(self): """Get last aggregation date.""" if not Index(self.aggregation_alias, using=self.client).exists(): if not Index(self.event_index, using=self.client).exists(): return datetime.date.today() return self._get_oldest_event_timestamp() # retrieve the oldest bookmark query_bookmark = Search( using=self.client, index=self.aggregation_alias, doc_type=self.bookmark_doc_type )[0:1].sort( {'date': {'order': 'desc'}} )
python
{ "resource": "" }
q261994
StatAggregator.set_bookmark
validation
def set_bookmark(self): """Set bookmark for starting next aggregation.""" def _success_date(): bookmark = { 'date': self.new_bookmark or datetime.datetime.utcnow().
python
{ "resource": "" }
q261995
StatAggregator._format_range_dt
validation
def _format_range_dt(self, d): """Format range filter datetime to the closest aggregation interval."""
python
{ "resource": "" }
q261996
StatAggregator.agg_iter
validation
def agg_iter(self, lower_limit=None, upper_limit=None): """Aggregate and return dictionary to be indexed in ES.""" lower_limit = lower_limit or self.get_bookmark().isoformat() upper_limit = upper_limit or ( datetime.datetime.utcnow().replace(microsecond=0).isoformat()) aggregation_data = {} self.agg_query = Search(using=self.client, index=self.event_index).\ filter('range', timestamp={ 'gte': self._format_range_dt(lower_limit), 'lte': self._format_range_dt(upper_limit)}) # apply query modifiers for modifier in self.query_modifiers: self.agg_query = modifier(self.agg_query) hist = self.agg_query.aggs.bucket( 'histogram', 'date_histogram', field='timestamp', interval=self.aggregation_interval ) terms = hist.bucket( 'terms', 'terms', field=self.aggregation_field, size=0 ) top = terms.metric( 'top_hit', 'top_hits', size=1, sort={'timestamp': 'desc'} ) for dst, (metric, src, opts) in self.metric_aggregation_fields.items(): terms.metric(dst, metric, field=src, **opts) results = self.agg_query.execute()
python
{ "resource": "" }
q261997
StatAggregator.run
validation
def run(self, start_date=None, end_date=None, update_bookmark=True): """Calculate statistics aggregations.""" # If no events have been indexed there is nothing to aggregate if not Index(self.event_index, using=self.client).exists(): return lower_limit = start_date or self.get_bookmark() # Stop here if no bookmark could be estimated. if lower_limit is None: return upper_limit = min( end_date or datetime.datetime.max, # ignore if `None` datetime.datetime.utcnow().replace(microsecond=0), datetime.datetime.combine( lower_limit + datetime.timedelta(self.batch_size), datetime.datetime.min.time()) ) while upper_limit <= datetime.datetime.utcnow(): self.indices = set() self.new_bookmark = upper_limit.strftime(self.doc_id_suffix) bulk(self.client, self.agg_iter(lower_limit, upper_limit), stats_only=True, chunk_size=50) # Flush all indices
python
{ "resource": "" }
q261998
StatAggregator.list_bookmarks
validation
def list_bookmarks(self, start_date=None, end_date=None, limit=None): """List the aggregation's bookmarks.""" query = Search( using=self.client, index=self.aggregation_alias, doc_type=self.bookmark_doc_type ).sort({'date': {'order': 'desc'}}) range_args = {} if start_date: range_args['gte'] = self._format_range_dt( start_date.replace(microsecond=0)) if end_date:
python
{ "resource": "" }
q261999
StatAggregator.delete
validation
def delete(self, start_date=None, end_date=None): """Delete aggregation documents.""" aggs_query = Search( using=self.client, index=self.aggregation_alias, doc_type=self.aggregation_doc_type ).extra(_source=False) range_args = {} if start_date: range_args['gte'] = self._format_range_dt( start_date.replace(microsecond=0)) if end_date: range_args['lte'] = self._format_range_dt( end_date.replace(microsecond=0)) if range_args: aggs_query = aggs_query.filter('range', timestamp=range_args) bookmarks_query = Search( using=self.client, index=self.aggregation_alias, doc_type=self.bookmark_doc_type ).sort({'date': {'order': 'desc'}}) if range_args: bookmarks_query = bookmarks_query.filter('range', date=range_args) def _delete_actions(): for query in (aggs_query, bookmarks_query): affected_indices = set()
python
{ "resource": "" }