INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Gets a re - labeled clone of this expression.
def relabeled_clone(self, relabels): """Gets a re-labeled clone of this expression.""" return self.__class__( relabels.get(self.alias, self.alias), self.target, self.hstore_key, self.output_field )
Resolves the expression into a: see: HStoreColumn expression.
def resolve_expression(self, *args, **kwargs) -> HStoreColumn: """Resolves the expression into a :see:HStoreColumn expression.""" original_expression = super().resolve_expression(*args, **kwargs) expression = HStoreColumn( original_expression.alias, original_expression.t...
Compiles this expression into SQL.
def as_sql(self, compiler, connection): """Compiles this expression into SQL.""" sql, params = super().as_sql(compiler, connection) return 'EXTRACT(epoch FROM {})'.format(sql), params
Renames the aliases for the specified annotations:
def rename_annotations(self, annotations) -> None: """Renames the aliases for the specified annotations: .annotate(myfield=F('somestuf__myfield')) .rename_annotations(myfield='field') Arguments: annotations: The annotations to rename. Mapping the ...
Adds an extra condition to an existing JOIN.
def add_join_conditions(self, conditions: Dict[str, Any]) -> None: """Adds an extra condition to an existing JOIN. This allows you to for example do: INNER JOIN othertable ON (mytable.id = othertable.other_id AND [extra conditions]) This does not work if nothing else in your query...
Adds the given ( model ) fields to the select set. The field names are added in the order specified.
def add_fields(self, field_names: List[str], allow_m2m: bool=True) -> bool: """ Adds the given (model) fields to the select set. The field names are added in the order specified. This overrides the base class's add_fields method. This is called by the .values() or .values_list()...
Gets whether the field with the specified name is a HStoreField.
def _is_hstore_field(self, field_name: str) -> Tuple[bool, Optional[models.Field]]: """Gets whether the field with the specified name is a HStoreField. Returns A tuple of a boolean indicating whether the field with the specified name is a HStoreField, and the ...
Sets the values to be used in this query.
def values(self, objs: List, insert_fields: List, update_fields: List=[]): """Sets the values to be used in this query. Insert fields are fields that are definitely going to be inserted, and if an existing row is found, are going to be overwritten with the specified value. ...
Ran when a new model is created.
def create_model(self, model): """Ran when a new model is created.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue self.add_field(model, field)
Ran when a model is being deleted.
def delete_model(self, model): """Ran when a model is being deleted.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue self.remove_field(model, field)
Ran when the name of a model is changed.
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue for key in self._iterate_required_keys(field): self...
Ran when a field is added to a model.
def add_field(self, model, field): """Ran when a field is added to a model.""" for key in self._iterate_required_keys(field): self._create_hstore_required( model._meta.db_table, field, key )
Ran when a field is removed from a model.
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for key in self._iterate_required_keys(field): self._drop_hstore_required( model._meta.db_table, field, key )
Ran when the configuration on a field changed.
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" is_old_field_hstore = isinstance(old_field, HStoreField) is_new_field_hstore = isinstance(new_field, HStoreField) if not is_old_field_hstore and not is_new_field_hstor...
Creates a REQUIRED CONSTRAINT for the specified hstore key.
def _create_hstore_required(self, table_name, field, key): """Creates a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_create.format( name=self.quote_name(name), ...
Renames an existing REQUIRED CONSTRAINT for the specified hstore key.
def _rename_hstore_required(self, old_table_name, new_table_name, old_field, new_field, key): """Renames an existing REQUIRED CONSTRAINT for the specified hstore key.""" old_name = self._required_constraint_name( old_table_name, old_field, key) ...
Drops a REQUIRED CONSTRAINT for the specified hstore key.
def _drop_hstore_required(self, table_name, field, key): """Drops a REQUIRED CONSTRAINT for the specified hstore key.""" name = self._required_constraint_name( table_name, field, key) sql = self.sql_hstore_required_drop.format( table=self.quote_name(table_name), ...
Gets the name for a CONSTRAINT that applies to a single hstore key.
def _required_constraint_name(table: str, field, key): """Gets the name for a CONSTRAINT that applies to a single hstore key. Arguments: table: The name of the table the field is a part of. field: The hstore field to creat...
Creates the actual SQL used when applying the migration.
def create_sql(self, model, schema_editor, using=''): """Creates the actual SQL used when applying the migration.""" if django.VERSION >= (2, 0): statement = super().create_sql(model, schema_editor, using) statement.template = self.sql_create_index statement.parts['co...
Serializes the: see: ConditionalUniqueIndex for the migrations file.
def deconstruct(self): """Serializes the :see:ConditionalUniqueIndex for the migrations file.""" path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__) path = path.replace('django.db.models.indexes', 'django.db.models') return path, (), {'fields': self.fields, 'name': self...
Creates a custom setup. py command.
def create_command(text, commands): """Creates a custom setup.py command.""" class CustomCommand(BaseCommand): description = text def run(self): for cmd in commands: subprocess.check_call(cmd) return CustomCommand
Gets the base class for the custom database back - end.
def _get_backend_base(): """Gets the base class for the custom database back-end. This should be the Django PostgreSQL back-end. However, some people are already using a custom back-end from another package. We are nice people and expose an option that allows them to configure the back-end we base ...
Ran when a new model is created.
def create_model(self, model): """Ran when a new model is created.""" super().create_model(model) for mixin in self.post_processing_mixins: mixin.create_model(model)
Ran when a model is being deleted.
def delete_model(self, model): """Ran when a model is being deleted.""" for mixin in self.post_processing_mixins: mixin.delete_model(model) super().delete_model(model)
Ran when the name of a model is changed.
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" super(SchemaEditor, self).alter_db_table( model, old_db_table, new_db_table ) for mixin in self.post_processing_mixins: mixin.alter_db_table( ...
Ran when a field is added to a model.
def add_field(self, model, field): """Ran when a field is added to a model.""" super(SchemaEditor, self).add_field(model, field) for mixin in self.post_processing_mixins: mixin.add_field(model, field)
Ran when a field is removed from a model.
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for mixin in self.post_processing_mixins: mixin.remove_field(model, field) super(SchemaEditor, self).remove_field(model, field)
Ran when the configuration on a field changed.
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" super(SchemaEditor, self).alter_field( model, old_field, new_field, strict ) for mixin in self.post_processing_mixins: mixin.alter_field( ...
Ran to prepare the configured database.
def prepare_database(self): """Ran to prepare the configured database. This is where we enable the `hstore` extension if it wasn't enabled yet.""" super().prepare_database() with self.cursor() as cursor: try: cursor.execute('CREATE EXTENSION IF NOT E...
Override the base class so it doesn t cast all values to strings.
def get_prep_value(self, value): """Override the base class so it doesn't cast all values to strings. psqlextra supports expressions in hstore fields, so casting all values to strings is a bad idea.""" value = Field.get_prep_value(self, value) if isinstance(value, dict...
Gets the values to pass to: see: __init__ when re - creating this object.
def deconstruct(self): """Gets the values to pass to :see:__init__ when re-creating this object.""" name, path, args, kwargs = super( HStoreField, self).deconstruct() if self.uniqueness is not None: kwargs['uniqueness'] = self.uniqueness if self.require...
Extra prep on query values by converting dictionaries into: see: HStoreValue expressions.
def _prepare_query_values(self): """Extra prep on query values by converting dictionaries into :see:HStoreValue expressions. This allows putting expressions in a dictionary. The :see:HStoreValue will take care of resolving the expressions inside the dictionary.""" new_q...
Builds the RETURNING part of the query.
def _form_returning(self): """Builds the RETURNING part of the query.""" qn = self.connection.ops.quote_name return ' RETURNING %s' % qn(self.query.model._meta.pk.attname)
Builds the SQL INSERT statement.
def as_sql(self, return_id=False): """Builds the SQL INSERT statement.""" queries = [ self._rewrite_insert(sql, params, return_id) for sql, params in super().as_sql() ] return queries
Rewrites a formed SQL INSERT query to include the ON CONFLICT clause.
def _rewrite_insert(self, sql, params, return_id=False): """Rewrites a formed SQL INSERT query to include the ON CONFLICT clause. Arguments: sql: The SQL INSERT query to rewrite. params: The parameters passed to the query. re...
Rewrites a formed SQL INSERT query to include the ON CONFLICT DO UPDATE clause.
def _rewrite_insert_update(self, sql, params, returning): """Rewrites a formed SQL INSERT query to include the ON CONFLICT DO UPDATE clause.""" update_columns = ', '.join([ '{0} = EXCLUDED.{0}'.format(self.qn(field.column)) for field in self.query.update_fields ]...
Rewrites a formed SQL INSERT query to include the ON CONFLICT DO NOTHING clause.
def _rewrite_insert_nothing(self, sql, params, returning): """Rewrites a formed SQL INSERT query to include the ON CONFLICT DO NOTHING clause.""" # build the conflict target, the columns to watch # for conflicts conflict_target = self._build_conflict_target() where_clau...
Builds the conflict_target for the ON CONFLICT clause.
def _build_conflict_target(self): """Builds the `conflict_target` for the ON CONFLICT clause.""" conflict_target = [] if not isinstance(self.query.conflict_target, list): raise SuspiciousOperation(( '%s is not a valid conflict target, specify ' ...
Gets the field on a model with the specified name.
def _get_model_field(self, name: str): """Gets the field on a model with the specified name. Arguments: name: The name of the field to look for. This can be both the actual field name, or the name of the column, both will work :) Ret...
Formats a field s name for usage in SQL.
def _format_field_name(self, field_name) -> str: """Formats a field's name for usage in SQL. Arguments: field_name: The field name to format. Returns: The specified field name formatted for usage in SQL. """ field = self._get...
Formats a field s value for usage in SQL.
def _format_field_value(self, field_name) -> str: """Formats a field's value for usage in SQL. Arguments: field_name: The name of the field to format the value of. Returns: The field's value formatted for usage in SQL. ...
Normalizes a field name into a string by extracting the field name if it was specified as a reference to a HStore key ( as a tuple ).
def _normalize_field_name(self, field_name) -> str: """Normalizes a field name into a string by extracting the field name if it was specified as a reference to a HStore key (as a tuple). Arguments: field_name: The field name to normalize. Returns: ...
Ran when the name of a model is changed.
def alter_db_table(self, model, old_db_table, new_db_table): """Ran when the name of a model is changed.""" for field in model._meta.local_fields: if not isinstance(field, HStoreField): continue for keys in self._iterate_uniqueness_keys(field): s...
Ran when a field is added to a model.
def add_field(self, model, field): """Ran when a field is added to a model.""" for keys in self._iterate_uniqueness_keys(field): self._create_hstore_unique( model, field, keys )
Ran when a field is removed from a model.
def remove_field(self, model, field): """Ran when a field is removed from a model.""" for keys in self._iterate_uniqueness_keys(field): self._drop_hstore_unique( model, field, keys )
Ran when the configuration on a field changed.
def alter_field(self, model, old_field, new_field, strict=False): """Ran when the configuration on a field changed.""" is_old_field_hstore = isinstance(old_field, HStoreField) is_new_field_hstore = isinstance(new_field, HStoreField) if not is_old_field_hstore and not is_new_field_hstor...
Creates a UNIQUE constraint for the specified hstore keys.
def _create_hstore_unique(self, model, field, keys): """Creates a UNIQUE constraint for the specified hstore keys.""" name = self._unique_constraint_name( model._meta.db_table, field, keys) columns = [ '(%s->\'%s\')' % (field.column, key) for key in keys ...
Renames an existing UNIQUE constraint for the specified hstore keys.
def _rename_hstore_unique(self, old_table_name, new_table_name, old_field, new_field, keys): """Renames an existing UNIQUE constraint for the specified hstore keys.""" old_name = self._unique_constraint_name( old_table_name, old_field, keys) new...
Drops a UNIQUE constraint for the specified hstore keys.
def _drop_hstore_unique(self, model, field, keys): """Drops a UNIQUE constraint for the specified hstore keys.""" name = self._unique_constraint_name( model._meta.db_table, field, keys) sql = self.sql_hstore_unique_drop.format(name=self.quote_name(name)) self.execute(sql)
Gets the name for a UNIQUE INDEX that applies to one or more keys in a hstore field.
def _unique_constraint_name(table: str, field, keys): """Gets the name for a UNIQUE INDEX that applies to one or more keys in a hstore field. Arguments: table: The name of the table the field is a part of. field: The hstor...
Iterates over the keys marked as unique in the specified field.
def _iterate_uniqueness_keys(self, field): """Iterates over the keys marked as "unique" in the specified field. Arguments: field: The field of which key's to iterate over. """ uniqueness = getattr(field, 'uniqueness', None) if...
Adds an extra condition to this join.
def add_condition(self, field, value: Any) -> None: """Adds an extra condition to this join. Arguments: field: The field that the condition will apply to. value: The value to compare. """ self.extra_conditions.append((field, valu...
Compiles this JOIN into a SQL string.
def as_sql(self, compiler, connection) -> Tuple[str, List[Any]]: """Compiles this JOIN into a SQL string.""" sql, params = super().as_sql(compiler, connection) qn = compiler.quote_name_unless_alias # generate the extra conditions extra_conditions = ' AND '.join([ '{...
Creates a new: see: ConditionalJoin from the specified: see: Join object.
def from_join(cls, join: Join) -> 'ConditionalJoin': """Creates a new :see:ConditionalJoin from the specified :see:Join object. Arguments: join: The :see:Join object to create the :see:ConditionalJoin object from. Returns: A :see:...
Approximate the 95% confidence interval for Student s T distribution.
def tdist95conf_level(df): """Approximate the 95% confidence interval for Student's T distribution. Given the degrees of freedom, returns an approximation to the 95% confidence interval for the Student's T distribution. Args: df: An integer, the number of degrees of freedom. Returns: ...
Find the pooled sample variance for two samples.
def pooled_sample_variance(sample1, sample2): """Find the pooled sample variance for two samples. Args: sample1: one sample. sample2: the other sample. Returns: Pooled sample variance, as a float. """ deg_freedom = len(sample1) + len(sample2) - 2 mean1 = statistics.mean...
Calculate a t - test score for the difference between two samples.
def tscore(sample1, sample2): """Calculate a t-test score for the difference between two samples. Args: sample1: one sample. sample2: the other sample. Returns: The t-test score, as a float. """ if len(sample1) != len(sample2): raise ValueError("different number of ...
Determine whether two samples differ significantly.
def is_significant(sample1, sample2): """Determine whether two samples differ significantly. This uses a Student's two-sample, two-tailed t-test with alpha=0.95. Args: sample1: one sample. sample2: the other sample. Returns: (significant, t_score) where significant is a bool i...
Return a topological sorting of nodes in a graph.
def topoSort(roots, getParents): """Return a topological sorting of nodes in a graph. roots - list of root nodes to search from getParents - function which returns the parents of a given node """ results = [] visited = set() # Use iterative version to avoid stack limits for large datasets...
permutations ( range ( 3 ) 2 ) -- > ( 0 1 ) ( 0 2 ) ( 1 0 ) ( 1 2 ) ( 2 0 ) ( 2 1 )
def permutations(iterable, r=None): """permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)""" pool = tuple(iterable) n = len(pool) if r is None: r = n indices = list(range(n)) cycles = list(range(n - r + 1, n + 1))[::-1] yield tuple(pool[i] for i in indices[:r]) whi...
N - Queens solver.
def n_queens(queen_count): """N-Queens solver. Args: queen_count: the number of queens to solve for. This is also the board size. Yields: Solutions to the problem. Each yielded value is looks like (3, 8, 2, 1, 4, ..., 6) where each number is the column position for the ...
uct tree search
def play(self, board): """ uct tree search """ color = board.color node = self path = [node] while True: pos = node.select(board) if pos == PASS: break board.move(pos) child = node.pos_child[pos] if not c...
select move ; unexplored children first then according to uct value
def select(self, board): """ select move; unexplored children first, then according to uct value """ if self.unexplored: i = random.randrange(len(self.unexplored)) pos = self.unexplored[i] self.unexplored[i] = self.unexplored[len(self.unexplored) - 1] self...
random play until both players pass
def random_playout(self, board): """ random play until both players pass """ for x in range(MAXMOVES): # XXX while not self.finished? if board.finished: break board.move(board.random_move())
update win/ loss count along path
def update_path(self, board, color, path): """ update win/loss count along path """ wins = board.score(BLACK) >= board.score(WHITE) for node in path: if color == BLACK: color = WHITE else: color = BLACK if wins == (color == BLAC...
Filters out benchmarks not supported by both Pythons.
def filter_benchmarks(benchmarks, bench_funcs, base_ver): """Filters out benchmarks not supported by both Pythons. Args: benchmarks: a set() of benchmark names bench_funcs: dict mapping benchmark names to functions python: the interpereter commands (as lists) Returns: The f...
Recursively expand name benchmark names.
def expand_benchmark_name(bm_name, bench_groups): """Recursively expand name benchmark names. Args: bm_name: string naming a benchmark or benchmark group. Yields: Names of actual benchmarks, with all group names fully expanded. """ expansion = bench_groups.get(bm_name) if expan...
Generates the list of strings that will be used in the benchmarks.
def gen_string_table(n): """Generates the list of strings that will be used in the benchmarks. All strings have repeated prefixes and suffices, and n specifies the number of repetitions. """ strings = [] def append(s): if USE_BYTES_IN_PY3K: strings.append(s.encode('latin1')...
Initialize the strings we ll run the regexes against.
def init_benchmarks(n_values=None): """Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values of n from the original benc...
Pure - Python implementation of itertools. combinations ( l 2 ).
def combinations(l): """Pure-Python implementation of itertools.combinations(l, 2).""" result = [] for x in xrange(len(l) - 1): ls = l[x + 1:] for y in ls: result.append((l[x], y)) return result
Returns the domain of the B - Spline
def GetDomain(self): """Returns the domain of the B-Spline""" return (self.knots[self.degree - 1], self.knots[len(self.knots) - self.degree])
Fetch the messages.
def fetch_items(self, category, **kwargs): """Fetch the messages. :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Fetching messages of '%s' - '%s' c...
Init client
def _init_client(self, from_archive=False): """Init client""" return MattermostClient(self.url, self.api_token, max_items=self.max_items, sleep_for_rate=self.sleep_for_rate, min_rate_to_sleep=self.min_rate_t...
Parse posts and returns in order.
def _parse_posts(self, raw_posts): """Parse posts and returns in order.""" parsed_posts = self.parse_json(raw_posts) # Posts are not sorted. The order is provided by # 'order' key. for post_id in parsed_posts['order']: yield parsed_posts['posts'][post_id]
Fetch the history of a channel.
def posts(self, channel, page=None): """Fetch the history of a channel.""" entrypoint = self.RCHANNELS + '/' + channel + '/' + self.RPOSTS params = { self.PPER_PAGE: self.max_items } if page is not None: params[self.PPAGE] = page response = sel...
Fetch user data.
def user(self, user): """Fetch user data.""" entrypoint = self.RUSERS + '/' + user response = self._fetch(entrypoint, None) return response
Fetch a resource.
def _fetch(self, entry_point, params): """Fetch a resource. :param entrypoint: entrypoint to access :param params: dict with the HTTP parameters needed to access the given entry point """ url = self.API_URL % {'base_url': self.base_url, 'entrypoint': entry_point} ...
Initialize mailing lists directory path
def _pre_init(self): """Initialize mailing lists directory path""" if not self.parsed_args.mboxes_path: base_path = os.path.expanduser('~/.perceval/mailinglists/') dirpath = os.path.join(base_path, self.parsed_args.url) else: dirpath = self.parsed_args.mboxes...
Fetch the mbox files from the remote archiver.
def fetch(self, from_date=DEFAULT_DATETIME): """Fetch the mbox files from the remote archiver. Stores the archives in the path given during the initialization of this object. Those archives which a not valid extension will be ignored. Pipermail archives usually have on their fi...
Get the mboxes managed by this mailing list.
def mboxes(self): """Get the mboxes managed by this mailing list. Returns the archives sorted by date in ascending order. :returns: a list of `.MBoxArchive` objects """ archives = [] for mbox in super().mboxes: dt = self._parse_date_from_filepath(mbox.filep...
Fetch the entries from the url.
def fetch(self, category=CATEGORY_ENTRY): """Fetch the entries from the url. The method retrieves all entries from a RSS url :param category: the category of items to fetch :returns: a generator of entries """ kwargs = {} items = super().fetch(category, **kwarg...
Fetch the entries
def fetch_items(self, category, **kwargs): """Fetch the entries :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ logger.info("Looking for rss entries at feed '%s'", self.url) nentries = 0 # num...
Init client
def _init_client(self, from_archive=False): """Init client""" return RSSClient(self.url, self.archive, from_archive)
Returns the RSS argument parser.
def setup_cmd_parser(cls): """Returns the RSS argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, archive=True) # Required arguments parser.parser.add_argument('url', help="UR...
Fetch the bugs from the repository.
def fetch(self, category=CATEGORY_BUG, from_date=DEFAULT_DATETIME): """Fetch the bugs from the repository. The method retrieves, from a Bugzilla repository, the bugs updated since the given date. :param category: the category of items to fetch :param from_date: obtain bugs upda...
Fetch the bugs
def fetch_items(self, category, **kwargs): """Fetch the bugs :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] logger.info("Looking for bugs: '%s' updated from '%...
Init client
def _init_client(self, from_archive=False): """Init client""" return BugzillaRESTClient(self.url, user=self.user, password=self.password, api_token=self.api_token, archive=self.archive, from_archive=from_archive)
Authenticate a user in the server.
def login(self, user, password): """Authenticate a user in the server. :param user: Bugzilla user :param password: user password """ params = { self.PBUGZILLA_LOGIN: user, self.PBUGZILLA_PASSWORD: password } try: r = self.call...
Get the information of a list of bugs.
def bugs(self, from_date=DEFAULT_DATETIME, offset=None, max_bugs=MAX_BUGS): """Get the information of a list of bugs. :param from_date: retrieve bugs that where updated from that date; dates are converted to UTC :param offset: starting position for the search; i.e to return 11th ...
Get the comments of the given bugs.
def comments(self, *bug_ids): """Get the comments of the given bugs. :param bug_ids: list of bug identifiers """ # Hack. The first value must be a valid bug id resource = urijoin(self.RBUG, bug_ids[0], self.RCOMMENT) params = { self.PIDS: bug_ids } ...
Get the history of the given bugs.
def history(self, *bug_ids): """Get the history of the given bugs. :param bug_ids: list of bug identifiers """ resource = urijoin(self.RBUG, bug_ids[0], self.RHISTORY) params = { self.PIDS: bug_ids } response = self.call(resource, params) r...
Get the attachments of the given bugs.
def attachments(self, *bug_ids): """Get the attachments of the given bugs. :param bug_id: list of bug identifiers """ resource = urijoin(self.RBUG, bug_ids[0], self.RATTACHMENT) params = { self.PIDS: bug_ids, self.PEXCLUDE_FIELDS: self.VEXCLUDE_ATTCH_DAT...
Retrive the given resource.
def call(self, resource, params): """Retrive the given resource. :param resource: resource to retrieve :param params: dict with the HTTP parameters needed to retrieve the given resource :raises BugzillaRESTError: raised when an error is returned by the server ...
Sanitize payload of a HTTP request by removing the login password and token information before storing/ retrieving archived items
def sanitize_for_archive(url, headers, payload): """Sanitize payload of a HTTP request by removing the login, password and token information before storing/retrieving archived items :param: url: HTTP url request :param: headers: HTTP headers request :param: payload: HTTP payload...
Fetch the items ( issues or merge_requests )
def fetch_items(self, category, **kwargs): """Fetch the items (issues or merge_requests) :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_...
Fetch the issues
def __fetch_issues(self, from_date): """Fetch the issues""" issues_groups = self.client.issues(from_date=from_date) for raw_issues in issues_groups: issues = json.loads(raw_issues) for issue in issues: issue_id = issue['iid'] if self.bla...
Get issue notes
def __get_issue_notes(self, issue_id): """Get issue notes""" notes = [] group_notes = self.client.notes(GitLabClient.ISSUES, issue_id) for raw_notes in group_notes: for note in json.loads(raw_notes): note_id = note['id'] note['award_emoji_d...
Fetch the merge requests
def __fetch_merge_requests(self, from_date): """Fetch the merge requests""" merges_groups = self.client.merges(from_date=from_date) for raw_merges in merges_groups: merges = json.loads(raw_merges) for merge in merges: merge_id = merge['iid'] ...
Get merge notes
def __get_merge_notes(self, merge_id): """Get merge notes""" notes = [] group_notes = self.client.notes(GitLabClient.MERGES, merge_id) for raw_notes in group_notes: for note in json.loads(raw_notes): note_id = note['id'] note['award_emoji_da...
Get merge versions
def __get_merge_versions(self, merge_id): """Get merge versions""" versions = [] group_versions = self.client.merge_versions(merge_id) for raw_versions in group_versions: for version in json.loads(raw_versions): version_id = version['id'] ve...