_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q234700
AccountGroup.oauth_client_create
train
def oauth_client_create(self, name, redirect_uri, **kwargs): """ Make a new OAuth Client and return it """ params = { "label": name, "redirect_uri": redirect_uri, } params.update(kwargs) result = self.client.post('/account/oauth-clients', ...
python
{ "resource": "" }
q234701
AccountGroup.transfer
train
def transfer(self): """ Returns a MappedObject containing the account's transfer pool data """ result = self.client.get('/account/transfer') if not 'used' in result: raise UnexpectedResponseError('Unexpected response when getting Transfer Pool!') return Mapp...
python
{ "resource": "" }
q234702
NetworkingGroup.ip_allocate
train
def ip_allocate(self, linode, public=True): """ Allocates an IP to a Instance you own. Additional IPs must be requested by opening a support ticket first. :param linode: The Instance to allocate the new IP for. :type linode: Instance or int :param public: If True, alloc...
python
{ "resource": "" }
q234703
LinodeClient.load
train
def load(self, target_type, target_id, target_parent_id=None): """ Constructs and immediately loads the object, circumventing the lazy-loading scheme by immediately making an API request. Does not load related objects. For example, if you wanted to load an :any:`Instance` objec...
python
{ "resource": "" }
q234704
LinodeClient._api_call
train
def _api_call(self, endpoint, model=None, method=None, data=None, filters=None): """ Makes a call to the linode api. Data should only be given if the method is POST or PUT, and should be a dictionary """ if not self.token: raise RuntimeError("You do not have an API t...
python
{ "resource": "" }
q234705
LinodeClient.image_create
train
def image_create(self, disk, label=None, description=None): """ Creates a new Image from a disk you own. :param disk: The Disk to imagize. :type disk: Disk or int :param label: The label for the resulting Image (defaults to the disk's label. :type l...
python
{ "resource": "" }
q234706
LinodeClient.nodebalancer_create
train
def nodebalancer_create(self, region, **kwargs): """ Creates a new NodeBalancer in the given Region. :param region: The Region in which to create the NodeBalancer. :type region: Region or str :returns: The new NodeBalancer :rtype: NodeBalancer """ params...
python
{ "resource": "" }
q234707
LinodeClient.domain_create
train
def domain_create(self, domain, master=True, **kwargs): """ Registers a new Domain on the acting user's account. Make sure to point your registrar to Linode's nameservers so that Linode's DNS manager will correctly serve your domain. :param domain: The domain to register to Lin...
python
{ "resource": "" }
q234708
LinodeClient.tag_create
train
def tag_create(self, label, instances=None, domains=None, nodebalancers=None, volumes=None, entities=[]): """ Creates a new Tag and optionally applies it to the given entities. :param label: The label for the new Tag :type label: str :param entities: A list of...
python
{ "resource": "" }
q234709
LinodeClient.volume_create
train
def volume_create(self, label, region=None, linode=None, size=20, **kwargs): """ Creates a new Block Storage Volume, either in the given Region or attached to the given Instance. :param label: The label for the new Volume. :type label: str :param region: The Region to cr...
python
{ "resource": "" }
q234710
LinodeLoginClient.expire_token
train
def expire_token(self, token): """ Given a token, makes a request to the authentication server to expire it immediately. This is considered a responsible way to log out a user. If you simply remove the session your application has for the user without expiring their token, the ...
python
{ "resource": "" }
q234711
Profile.grants
train
def grants(self): """ Returns grants for the current user """ from linode_api4.objects.account import UserGrants resp = self._client.get('/profile/grants') # use special endpoint for restricted users grants = None if resp is not None: # if resp is Non...
python
{ "resource": "" }
q234712
Profile.add_whitelist_entry
train
def add_whitelist_entry(self, address, netmask, note=None): """ Adds a new entry to this user's IP whitelist, if enabled """ result = self._client.post("{}/whitelist".format(Profile.api_endpoint), data={ "address": address, "netmask...
python
{ "resource": "" }
q234713
AuthenticationForm.confirm_login_allowed
train
def confirm_login_allowed(self, user): """ Controls whether the given User may log in. This is a policy setting, independent of end-user authentication. This default behavior is to allow login by active users, and reject login by inactive users. If the given user cannot log in, ...
python
{ "resource": "" }
q234714
broken_chains
train
def broken_chains(samples, chains): """Find the broken chains. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): ...
python
{ "resource": "" }
q234715
discard
train
def discard(samples, chains): """Discard broken chains. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (list[array_like]): ...
python
{ "resource": "" }
q234716
majority_vote
train
def majority_vote(samples, chains): """Use the most common element in broken chains. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1. chains (li...
python
{ "resource": "" }
q234717
weighted_random
train
def weighted_random(samples, chains): """Determine the sample values of chains by weighed random choice. Args: samples (array_like): Samples as a nS x nV array_like object where nS is the number of samples and nV is the number of variables. The values should all be 0/1 or -1/+1....
python
{ "resource": "" }
q234718
DWaveSampler.validate_anneal_schedule
train
def validate_anneal_schedule(self, anneal_schedule): """Raise an exception if the specified schedule is invalid for the sampler. Args: anneal_schedule (list): An anneal schedule variation is defined by a series of pairs of floating-point numbers identifying p...
python
{ "resource": "" }
q234719
target_to_source
train
def target_to_source(target_adjacency, embedding): """Derive the source adjacency from an embedding and target adjacency. Args: target_adjacency (dict/:class:`networkx.Graph`): A dict of the form {v: Nv, ...} where v is a node in the target graph and Nv is the neighbors of v as ...
python
{ "resource": "" }
q234720
chain_to_quadratic
train
def chain_to_quadratic(chain, target_adjacency, chain_strength): """Determine the quadratic biases that induce the given chain. Args: chain (iterable): The variables that make up a chain. target_adjacency (dict/:class:`networkx.Graph`): Should be a dict of the form {s: ...
python
{ "resource": "" }
q234721
chain_break_frequency
train
def chain_break_frequency(samples_like, embedding): """Determine the frequency of chain breaks in the given samples. Args: samples_like (samples_like/:obj:`dimod.SampleSet`): A collection of raw samples. 'samples_like' is an extension of NumPy's array_like. See :func:`dimod.as_s...
python
{ "resource": "" }
q234722
edgelist_to_adjacency
train
def edgelist_to_adjacency(edgelist): """Converts an iterator of edges to an adjacency dict. Args: edgelist (iterable): An iterator over 2-tuples where each 2-tuple is an edge. Returns: dict: The adjacency dict. A dict of the form {v: Nv, ...} where v is a node in a graph and ...
python
{ "resource": "" }
q234723
TilingComposite.sample
train
def sample(self, bqm, **kwargs): """Sample from the specified binary quadratic model. Args: bqm (:obj:`dimod.BinaryQuadraticModel`): Binary quadratic model to be sampled from. **kwargs: Optional keyword arguments for the sampling method, specifie...
python
{ "resource": "" }
q234724
cache_connect
train
def cache_connect(database=None): """Returns a connection object to a sqlite database. Args: database (str, optional): The path to the database the user wishes to connect to. If not specified, a default is chosen using :func:`.cache_file`. If the special database name ':memory:'...
python
{ "resource": "" }
q234725
insert_chain
train
def insert_chain(cur, chain, encoded_data=None): """Insert a chain into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chain (iterable): A collection of nodes. Chains in embedding act a...
python
{ "resource": "" }
q234726
iter_chain
train
def iter_chain(cur): """Iterate over all of the chains in the database. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: list: The chain. """ select = "SELECT nodes FROM chain" for node...
python
{ "resource": "" }
q234727
insert_system
train
def insert_system(cur, system_name, encoded_data=None): """Insert a system name into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. system_name (str): The unique name of a system ...
python
{ "resource": "" }
q234728
insert_flux_bias
train
def insert_flux_bias(cur, chain, system, flux_bias, chain_strength, encoded_data=None): """Insert a flux bias offset into the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. chain (iterable): ...
python
{ "resource": "" }
q234729
get_flux_biases_from_cache
train
def get_flux_biases_from_cache(cur, chains, system_name, chain_strength, max_age=3600): """Determine the flux biases for all of the the given chains, system and chain strength. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` stat...
python
{ "resource": "" }
q234730
insert_graph
train
def insert_graph(cur, nodelist, edgelist, encoded_data=None): """Insert a graph into the cache. A graph is stored by number of nodes, number of edges and a json-encoded list of edges. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a ...
python
{ "resource": "" }
q234731
select_embedding_from_tag
train
def select_embedding_from_tag(cur, embedding_tag, target_nodelist, target_edgelist): """Select an embedding from the given tag and target graph. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. source_nodelist ...
python
{ "resource": "" }
q234732
select_embedding_from_source
train
def select_embedding_from_source(cur, source_nodelist, source_edgelist, target_nodelist, target_edgelist): """Select an embedding from the source graph and target graph. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run...
python
{ "resource": "" }
q234733
draw_chimera_bqm
train
def draw_chimera_bqm(bqm, width=None, height=None): """Draws a Chimera Graph representation of a Binary Quadratic Model. If cell width and height not provided assumes square cell dimensions. Throws an error if drawing onto a Chimera graph of the given dimensions fails. Args: bqm (:obj:`dimod.B...
python
{ "resource": "" }
q234734
embed_bqm
train
def embed_bqm(source_bqm, embedding, target_adjacency, chain_strength=1.0, smear_vartype=None): """Embed a binary quadratic model onto a target graph. Args: source_bqm (:obj:`.BinaryQuadraticModel`): Binary quadratic model to embed. embedding (dict): Mappi...
python
{ "resource": "" }
q234735
embed_ising
train
def embed_ising(source_h, source_J, embedding, target_adjacency, chain_strength=1.0): """Embed an Ising problem onto a target graph. Args: source_h (dict[variable, bias]/list[bias]): Linear biases of the Ising problem. If a list, the list's indices are used as variable labels. ...
python
{ "resource": "" }
q234736
embed_qubo
train
def embed_qubo(source_Q, embedding, target_adjacency, chain_strength=1.0): """Embed a QUBO onto a target graph. Args: source_Q (dict[(variable, variable), bias]): Coefficients of a quadratic unconstrained binary optimization (QUBO) model. embedding (dict): Mapping from ...
python
{ "resource": "" }
q234737
unembed_sampleset
train
def unembed_sampleset(target_sampleset, embedding, source_bqm, chain_break_method=None, chain_break_fraction=False): """Unembed the samples set. Construct a sample set for the source binary quadratic model (BQM) by unembedding the given samples from the target BQM. Args: ...
python
{ "resource": "" }
q234738
LazyFixedEmbeddingComposite.sample
train
def sample(self, bqm, chain_strength=1.0, chain_break_fraction=True, **parameters): """Sample the binary quadratic model. Note: At the initial sample(..) call, it will find a suitable embedding and initialize the remaining attributes before sampling the bqm. All following sample(..) calls will ...
python
{ "resource": "" }
q234739
_accumulate_random
train
def _accumulate_random(count, found, oldthing, newthing): """This performs on-line random selection. We have a stream of objects o_1,c_1; o_2,c_2; ... where there are c_i equivalent objects like o_1. We'd like to pick a random object o uniformly at random from the list [o_1]*c_1 + [...
python
{ "resource": "" }
q234740
_bulk_to_linear
train
def _bulk_to_linear(M, N, L, qubits): "Converts a list of chimera coordinates to linear indices." return [2 * L * N * x + 2 * L * y + L * u + k for x, y, u, k in qubits]
python
{ "resource": "" }
q234741
_to_linear
train
def _to_linear(M, N, L, q): "Converts a qubit in chimera coordinates to its linear index." (x, y, u, k) = q return 2 * L * N * x + 2 * L * y + L * u + k
python
{ "resource": "" }
q234742
_bulk_to_chimera
train
def _bulk_to_chimera(M, N, L, qubits): "Converts a list of linear indices to chimera coordinates." return [(q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L) for q in qubits]
python
{ "resource": "" }
q234743
_to_chimera
train
def _to_chimera(M, N, L, q): "Converts a qubit's linear index to chimera coordinates." return (q // N // L // 2, (q // L // 2) % N, (q // L) % 2, q % L)
python
{ "resource": "" }
q234744
eden_processor._compute_vline_scores
train
def _compute_vline_scores(self): """Does the hard work to prepare ``vline_score``. """ M, N, L = self.M, self.N, self.L vline_score = {} for x in range(M): laststart = [0 if (x, 0, 1, k) in self else None for k in range(L)] for y in range(N): ...
python
{ "resource": "" }
q234745
eden_processor._compute_hline_scores
train
def _compute_hline_scores(self): """Does the hard work to prepare ``hline_score``. """ M, N, L = self.M, self.N, self.L hline_score = {} for y in range(N): laststart = [0 if (0, y, 0, k) in self else None for k in range(L)] for x in range(M): ...
python
{ "resource": "" }
q234746
eden_processor.biclique
train
def biclique(self, xmin, xmax, ymin, ymax): """Compute a maximum-sized complete bipartite graph contained in the rectangle defined by ``xmin, xmax, ymin, ymax`` where each chain of qubits is either a vertical line or a horizontal line. INPUTS: xmin,xmax,ymin,ymax: integers d...
python
{ "resource": "" }
q234747
eden_processor._contains_line
train
def _contains_line(self, line): """Test if a chain of qubits is completely contained in ``self``. In particular, test if all qubits are present and the couplers connecting those qubits are also connected. NOTE: this function assumes that ``line`` is a list or tuple of qubits wh...
python
{ "resource": "" }
q234748
eden_processor.maximum_ell_bundle
train
def maximum_ell_bundle(self, ell): """Return a maximum ell bundle in the rectangle bounded by :math:`\{x0,x1\} \\times \{y0,y1\}` with vertical component :math:`(x0,y0) ... (x0,y1) = {x0} \\times \{y0,...,y1\}` and horizontal component :math:`(x0,y0) ... ...
python
{ "resource": "" }
q234749
eden_processor.nativeCliqueEmbed
train
def nativeCliqueEmbed(self, width): """Compute a maximum-sized native clique embedding in an induced subgraph of chimera with all chainlengths ``width+1``. INPUTS: width: width of the squares to search, also `chainlength`-1 OUTPUT: score: the score for the retur...
python
{ "resource": "" }
q234750
processor._compute_all_deletions
train
def _compute_all_deletions(self): """Returns all minimal edge covers of the set of evil edges. """ minimum_evil = [] for disabled_qubits in map(set, product(*self._evil)): newmin = [] for s in minimum_evil: if s < disabled_qubits: ...
python
{ "resource": "" }
q234751
processor._compute_deletions
train
def _compute_deletions(self): """If there are fewer than self._proc_limit possible deletion sets, compute all subprocessors obtained by deleting a minimal subset of qubits. """ M, N, L, edgelist = self.M, self.N, self.L, self._edgelist if 2**len(self._evil) <= self._proc_...
python
{ "resource": "" }
q234752
processor._random_subprocessor
train
def _random_subprocessor(self): """Creates a random subprocessor where there is a coupler between every pair of working qubits on opposite sides of the same cell. This is guaranteed to be minimal in that adding a qubit back in will reintroduce a bad coupler, but not to have minimum size....
python
{ "resource": "" }
q234753
processor._objective_bestscore
train
def _objective_bestscore(self, old, new): """An objective function that returns True if new has a better score than old, and ``False`` otherwise. INPUTS: old (tuple): a tuple (score, embedding) new (tuple): a tuple (score, embedding) """ (oldscore, oldt...
python
{ "resource": "" }
q234754
processor.nativeCliqueEmbed
train
def nativeCliqueEmbed(self, width): """Compute a maximum-sized native clique embedding in an induced subgraph of chimera with chainsize ``width+1``. If possible, returns a uniform choice among all largest cliques. INPUTS: width: width of the squares to search, also `chainle...
python
{ "resource": "" }
q234755
processor._translate
train
def _translate(self, embedding): "Translates an embedding back to linear coordinates if necessary." if embedding is None: return None if not self._linear: return embedding return [_bulk_to_linear(self.M, self.N, self.L, chain) for chain in embedding]
python
{ "resource": "" }
q234756
_validate_chain_strength
train
def _validate_chain_strength(sampler, chain_strength): """Validate the provided chain strength, checking J-ranges of the sampler's children. Args: chain_strength (float) The provided chain strength. Use None to use J-range. Returns (float): A valid chain strength, either provided or based...
python
{ "resource": "" }
q234757
VirtualGraphComposite.sample
train
def sample(self, bqm, apply_flux_bias_offsets=True, **kwargs): """Sample from the given Ising model. Args: h (list/dict): Linear biases of the Ising model. If a list, the list's indices are used as variable labels. J (dict of (int, int):float): ...
python
{ "resource": "" }
q234758
get_flux_biases
train
def get_flux_biases(sampler, embedding, chain_strength, num_reads=1000, max_age=3600): """Get the flux bias offsets for sampler and embedding. Args: sampler (:obj:`.DWaveSampler`): A D-Wave sampler. embedding (dict[hashable, iterable]): Mapping from a source graph to th...
python
{ "resource": "" }
q234759
find_clique_embedding
train
def find_clique_embedding(k, m, n=None, t=None, target_edges=None): """Find an embedding for a clique in a Chimera graph. Given a target :term:`Chimera` graph size, and a clique (fully connect graph), attempts to find an embedding. Args: k (int/iterable): Clique to embed. If k is a...
python
{ "resource": "" }
q234760
find_biclique_embedding
train
def find_biclique_embedding(a, b, m, n=None, t=None, target_edges=None): """Find an embedding for a biclique in a Chimera graph. Given a target :term:`Chimera` graph size, and a biclique (a bipartite graph where every vertex in a set in connected to all vertices in the other set), attempts to find an embed...
python
{ "resource": "" }
q234761
find_grid_embedding
train
def find_grid_embedding(dim, m, n=None, t=4): """Find an embedding for a grid in a Chimera graph. Given a target :term:`Chimera` graph size, and grid dimensions, attempts to find an embedding. Args: dim (iterable[int]): Sizes of each grid dimension. Length can be between 1 and 3. ...
python
{ "resource": "" }
q234762
CutOffComposite.sample
train
def sample(self, bqm, **parameters): """Cutoff and sample from the provided binary quadratic model. Removes interactions smaller than a given cutoff. Isolated variables (after the cutoff) are also removed. Note that if the problem had isolated variables before the cutoff, they ...
python
{ "resource": "" }
q234763
PolyCutOffComposite.sample_poly
train
def sample_poly(self, poly, **kwargs): """Cutoff and sample from the provided binary polynomial. Removes interactions smaller than a given cutoff. Isolated variables (after the cutoff) are also removed. Note that if the problem had isolated variables before the cutoff, they wil...
python
{ "resource": "" }
q234764
diagnose_embedding
train
def diagnose_embedding(emb, source, target): """A detailed diagnostic for minor embeddings. This diagnostic produces a generator, which lists all issues with `emb`. The errors are yielded in the form ExceptionClass, arg1, arg2,... where the arguments following the class are used to construct ...
python
{ "resource": "" }
q234765
Namespace.model
train
def model(self, name=None, model=None, mask=None, **kwargs): """ Model registration decorator. """ if isinstance(model, (flask_marshmallow.Schema, flask_marshmallow.base_fields.FieldABC)): if not name: name = model.__class__.__name__ api_model = Mo...
python
{ "resource": "" }
q234766
Namespace.parameters
train
def parameters(self, parameters, locations=None): """ Endpoint parameters registration decorator. """ def decorator(func): if locations is None and parameters.many: _locations = ('json', ) else: _locations = locations if...
python
{ "resource": "" }
q234767
Namespace.response
train
def response(self, model=None, code=HTTPStatus.OK, description=None, **kwargs): """ Endpoint response OpenAPI documentation decorator. It automatically documents HTTPError%(code)d responses with relevant schemas. Arguments: model (flask_marshmallow.Schema) - it can ...
python
{ "resource": "" }
q234768
Resource._apply_decorator_to_methods
train
def _apply_decorator_to_methods(cls, decorator): """ This helper can apply a given decorator to all methods on the current Resource. NOTE: In contrast to ``Resource.method_decorators``, which has a similar use-case, this method applies decorators directly and override me...
python
{ "resource": "" }
q234769
Resource.options
train
def options(self, *args, **kwargs): """ Check which methods are allowed. Use this method if you need to know what operations are allowed to be performed on this endpoint, e.g. to decide wether to display a button in your UI. The list of allowed methods is provided in `A...
python
{ "resource": "" }
q234770
PatchJSONParameters.validate_patch_structure
train
def validate_patch_structure(self, data): """ Common validation of PATCH structure Provide check that 'value' present in all operations expect it. Provide check if 'path' is present. 'path' can be absent if provided without '/' at the start. Supposed that if 'path' is present t...
python
{ "resource": "" }
q234771
PatchJSONParameters.perform_patch
train
def perform_patch(cls, operations, obj, state=None): """ Performs all necessary operations by calling class methods with corresponding names. """ if state is None: state = {} for operation in operations: if not cls._process_patch_operation(operatio...
python
{ "resource": "" }
q234772
PatchJSONParameters.replace
train
def replace(cls, obj, field, value, state): """ This is method for replace operation. It is separated to provide a possibility to easily override it in your Parameters. Args: obj (object): an instance to change. field (str): field name value (str): ne...
python
{ "resource": "" }
q234773
DiscourseEnrich.__related_categories
train
def __related_categories(self, category_id): """ Get all related categories to a given one """ related = [] for cat in self.categories_tree: if category_id in self.categories_tree[cat]: related.append(self.categories[cat]) return related
python
{ "resource": "" }
q234774
_create_projects_file
train
def _create_projects_file(project_name, data_source, items): """ Create a projects file from the items origin data """ repositories = [] for item in items: if item['origin'] not in repositories: repositories.append(item['origin']) projects = { project_name: { dat...
python
{ "resource": "" }
q234775
DockerHubEnrich.enrich_items
train
def enrich_items(self, ocean_backend, events=False): """ A custom enrich items is needed because apart from the enriched events from raw items, a image item with the last data for an image must be created """ max_items = self.elastic.max_items_bulk current = 0 total = 0 ...
python
{ "resource": "" }
q234776
get_owner_repos_url
train
def get_owner_repos_url(owner, token): """ The owner could be a org or a user. It waits if need to have rate limit. Also it fixes a djando issue changing - with _ """ url_org = GITHUB_API_URL + "/orgs/" + owner + "/repos" url_user = GITHUB_API_URL + "/users/" + owner + "/repos" url_...
python
{ "resource": "" }
q234777
get_repositores
train
def get_repositores(owner_url, token, nrepos): """ owner could be an org or and user """ all_repos = [] url = owner_url while True: logging.debug("Getting repos from: %s" % (url)) try: r = requests.get(url, params=get_payload(), ...
python
{ "resource": "" }
q234778
publish_twitter
train
def publish_twitter(twitter_contact, owner): """ Publish in twitter the dashboard """ dashboard_url = CAULDRON_DASH_URL + "/%s" % (owner) tweet = "@%s your http://cauldron.io dashboard for #%s at GitHub is ready: %s. Check it out! #oscon" \ % (twitter_contact, owner, dashboard_url) status = quot...
python
{ "resource": "" }
q234779
MediaWikiOcean.get_perceval_params_from_url
train
def get_perceval_params_from_url(cls, urls): """ Get the perceval params given the URLs for the data source """ params = [] dparam = cls.get_arthur_params_from_url(urls) params.append(dparam["url"]) return params
python
{ "resource": "" }
q234780
SortingHat.add_identity
train
def add_identity(cls, db, identity, backend): """ Load and identity list from backend in Sorting Hat """ uuid = None try: uuid = api.add_identity(db, backend, identity['email'], identity['name'], identity['username']) logger.debug("Ne...
python
{ "resource": "" }
q234781
SortingHat.add_identities
train
def add_identities(cls, db, identities, backend): """ Load identities list from backend in Sorting Hat """ logger.info("Adding the identities to SortingHat") total = 0 for identity in identities: try: cls.add_identity(db, identity, backend) ...
python
{ "resource": "" }
q234782
SortingHat.remove_identity
train
def remove_identity(cls, sh_db, ident_id): """Delete an identity from SortingHat. :param sh_db: SortingHat database :param ident_id: identity identifier """ success = False try: api.delete_identity(sh_db, ident_id) logger.debug("Identity %s delete...
python
{ "resource": "" }
q234783
SortingHat.remove_unique_identity
train
def remove_unique_identity(cls, sh_db, uuid): """Delete a unique identity from SortingHat. :param sh_db: SortingHat database :param uuid: Unique identity identifier """ success = False try: api.delete_unique_identity(sh_db, uuid) logger.debug("Uni...
python
{ "resource": "" }
q234784
SortingHat.unique_identities
train
def unique_identities(cls, sh_db): """List the unique identities available in SortingHat. :param sh_db: SortingHat database """ try: for unique_identity in api.unique_identities(sh_db): yield unique_identity except Exception as e: logger.d...
python
{ "resource": "" }
q234785
PuppetForgeEnrich.get_rich_events
train
def get_rich_events(self, item): """ Get the enriched events related to a module """ module = item['data'] if not item['data']['releases']: return [] for release in item['data']['releases']: event = self.get_rich_item(item) # Update sp...
python
{ "resource": "" }
q234786
Database._connect
train
def _connect(self): """Connect to the MySQL database. """ try: db = pymysql.connect(user=self.user, passwd=self.passwd, host=self.host, port=self.port, db=self.shdb, use_unicode=True) return db, db.cursor(...
python
{ "resource": "" }
q234787
refresh_identities
train
def refresh_identities(enrich_backend, author_field=None, author_values=None): """Refresh identities in enriched index. Retrieve items from the enriched index corresponding to enrich_backend, and update their identities information, with fresh data from the SortingHat database. Instead of the whol...
python
{ "resource": "" }
q234788
get_ocean_backend
train
def get_ocean_backend(backend_cmd, enrich_backend, no_incremental, filter_raw=None, filter_raw_should=None): """ Get the ocean backend configured to start from the last enriched date """ if no_incremental: last_enrich = None else: last_enrich = get_last_enrich(backend_...
python
{ "resource": "" }
q234789
do_studies
train
def do_studies(ocean_backend, enrich_backend, studies_args, retention_time=None): """Execute studies related to a given enrich backend. If `retention_time` is not None, the study data is deleted based on the number of minutes declared in `retention_time`. :param ocean_backend: backend to access raw items ...
python
{ "resource": "" }
q234790
delete_orphan_unique_identities
train
def delete_orphan_unique_identities(es, sortinghat_db, current_data_source, active_data_sources): """Delete all unique identities which appear in SortingHat, but not in the IDENTITIES_INDEX. :param es: ElasticSearchDSL object :param sortinghat_db: instance of the SortingHat database :param current_data...
python
{ "resource": "" }
q234791
delete_inactive_unique_identities
train
def delete_inactive_unique_identities(es, sortinghat_db, before_date): """Select the unique identities not seen before `before_date` and delete them from SortingHat. :param es: ElasticSearchDSL object :param sortinghat_db: instance of the SortingHat database :param before_date: datetime str to filt...
python
{ "resource": "" }
q234792
retain_identities
train
def retain_identities(retention_time, es_enrichment_url, sortinghat_db, data_source, active_data_sources): """Select the unique identities not seen before `retention_time` and delete them from SortingHat. Furthermore, it deletes also the orphan unique identities, those ones stored in SortingHat but not in I...
python
{ "resource": "" }
q234793
init_backend
train
def init_backend(backend_cmd): """Init backend within the backend_cmd""" try: backend_cmd.backend except AttributeError: parsed_args = vars(backend_cmd.parsed_args) init_args = find_signature_parameters(backend_cmd.BACKEND, parsed_args) ...
python
{ "resource": "" }
q234794
ElasticSearch.safe_index
train
def safe_index(cls, unique_id): """ Return a valid elastic index generated from unique_id """ index = unique_id if unique_id: index = unique_id.replace("/", "_").lower() return index
python
{ "resource": "" }
q234795
ElasticSearch._check_instance
train
def _check_instance(url, insecure): """Checks if there is an instance of Elasticsearch in url. Actually, it checks if GET on the url returns a JSON document with a field tagline "You know, for search", and a field version.number. :value url: url of the instance to check ...
python
{ "resource": "" }
q234796
ElasticSearch.safe_put_bulk
train
def safe_put_bulk(self, url, bulk_json): """ Bulk PUT controlling unicode issues """ headers = {"Content-Type": "application/x-ndjson"} try: res = self.requests.put(url + '?refresh=true', data=bulk_json, headers=headers) res.raise_for_status() except UnicodeEnco...
python
{ "resource": "" }
q234797
ElasticSearch.all_es_aliases
train
def all_es_aliases(self): """List all aliases used in ES""" r = self.requests.get(self.url + "/_aliases", headers=HEADER_JSON, verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError as ex: logger.warning("Something went wrong when retrieving...
python
{ "resource": "" }
q234798
ElasticSearch.list_aliases
train
def list_aliases(self): """List aliases linked to the index""" # check alias doesn't exist r = self.requests.get(self.index_url + "/_alias", headers=HEADER_JSON, verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError as ex: logger.wa...
python
{ "resource": "" }
q234799
ElasticSearch.bulk_upload
train
def bulk_upload(self, items, field_id): """Upload in controlled packs items to ES using bulk API""" current = 0 new_items = 0 # total items added with bulk bulk_json = "" if not items: return new_items url = self.index_url + '/items/_bulk' logger....
python
{ "resource": "" }