Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|># pylint: disable=g-direct-tensorflow-import # pylint: enable=g-direct-tensorflow-import __all__ = ['annotate_asset', 'make_and_track_object'] _ASSET_KEY_COLLECTION = 'tft_asset_key_collection' _ASSET_FILENAME_COLLECTION = 'tft_asset_filename_collection' # Thread-Hostile _OBJECT_...
module = TFGraphContext.get_module_to_export()
Using the snippet: <|code_start|> ... x_int = tft.compute_and_apply_vocabulary( ... inputs['x'], vocab_filename='my_vocab', ... num_oov_buckets=num_oov_buckets) ... depth = ( ... tft.experimental.get_vocabulary_size_by_name('my_vocab') + ... num_oov_buckets) ... x_encoded = tf.one_hot...
annotators.VOCABULARY_SIZE_BY_NAME_COLLECTION)
Predict the next line after this snippet: <|code_start|> class Command(NoArgsCommand): help = "reset all keys, triggering a request for all keys from the hub" def handle_noargs(self, **options): print 'resetting all keys for %s' % settings.LOCKSMITH_API_NAME endpoint = urljoin(settings.LOCKSMI...
apicall(endpoint, settings.LOCKSMITH_SIGNING_KEY,
Given the code snippet: <|code_start|> # loop over the rows for row in file: match = log_re.match(row) if match: record = match.groupdict() day = datetime.datetime.strptime(record['date'], log_date_format).date() if day == l...
apicall(
Predict the next line for this snippet: <|code_start|> class Command(NoArgsCommand): help = 'push keys that are marked as dirty to the hub' def handle_noargs(self, **options): verbosity = int(options.get('verbosity', 1)) endpoints = {UNPUBLISHED: 'create_key/', NEEDS_UPDATE: 'update_key/'} ...
apicall(endpoint, kps.api.signing_key, api=kps.api.name,
Using the snippet: <|code_start|> class Command(NoArgsCommand): help = 'push keys that are marked as dirty to the hub' def handle_noargs(self, **options): verbosity = int(options.get('verbosity', 1)) endpoints = {UNPUBLISHED: 'create_key/', NEEDS_UPDATE: 'update_key/'} actions = {UNPUBL...
dirty = KeyPublicationStatus.objects.exclude(status=PUBLISHED).filter(
Next line prediction: <|code_start|> class Command(NoArgsCommand): help = 'push keys that are marked as dirty to the hub' def handle_noargs(self, **options): verbosity = int(options.get('verbosity', 1)) <|code_end|> . Use current file imports: (import datetime import urllib2 from urlparse import urljo...
endpoints = {UNPUBLISHED: 'create_key/', NEEDS_UPDATE: 'update_key/'}
Predict the next line after this snippet: <|code_start|> class Command(NoArgsCommand): help = 'push keys that are marked as dirty to the hub' def handle_noargs(self, **options): verbosity = int(options.get('verbosity', 1)) endpoints = {UNPUBLISHED: 'create_key/', NEEDS_UPDATE: 'update_key/'} ...
dirty = KeyPublicationStatus.objects.exclude(status=PUBLISHED).filter(
Given snippet: <|code_start|> class Command(NoArgsCommand): help = 'push keys that are marked as dirty to the hub' def handle_noargs(self, **options): verbosity = int(options.get('verbosity', 1)) <|code_end|> , continue by predicting the next line. Consider current file imports: import datetime import...
endpoints = {UNPUBLISHED: 'create_key/', NEEDS_UPDATE: 'update_key/'}
Using the snippet: <|code_start|> class LocksmithBackend: """ Authenticate with email address/key. * Try to log in with email+password * If no user exists try and create one with key as password """ def authenticate(self, username=None, password=None): try: # if user exists...
key = Key.objects.get(email=username)
Given snippet: <|code_start|> ''' name = models.CharField(max_length=30) signing_key = models.CharField(max_length=32) url = models.URLField() push_enabled = models.BooleanField(default=True) description = models.TextField('Description', blank=True) status = models.IntegerField(choices=API_OP...
status = models.CharField(max_length=1, choices=KEY_STATUSES, default='U')
Next line prediction: <|code_start|> name = models.CharField('Name', max_length=100, blank=True, null=True, db_index=True) org_name = models.CharField('Organization Name', max_length=100, blank=True, null=True, db_index=True) org_url = models.CharFi...
status = models.IntegerField(default=UNPUBLISHED, choices=PUB_STATUSES)
Predict the next line after this snippet: <|code_start|> class Key(models.Model): ''' API key to be handed out to Apis ''' user = models.OneToOneField(User, null=True, blank=True, related_name='api_key') key = models.CharField(max_length=32, db_index=True) email = models.EmailField(unique=T...
self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE)
Using the snippet: <|code_start|> class Key(models.Model): ''' API key to be handed out to Apis ''' user = models.OneToOneField(User, null=True, blank=True, related_name='api_key') key = models.CharField(max_length=32, db_index=True) email = models.EmailField(unique=True) alternate_emai...
self.pub_statuses.exclude(status=UNPUBLISHED).update(status=NEEDS_UPDATE)
Using the snippet: <|code_start|>#from django.forms import Form, ModelForm, ValidationError, BooleanField, EmailField def resolve_model(model, fields): """ model: Model class fields: List of 2-tuples of the form (field, value) in order of descending priority """ for (f, v) in fields: if v i...
status = models.IntegerField(choices=API_OPERATING_STATUSES, default=1)
Given the code snippet: <|code_start|>#from django.forms import Form, ModelForm, ValidationError, BooleanField, EmailField def resolve_model(model, fields): """ model: Model class fields: List of 2-tuples of the form (field, value) in order of descending priority """ for (f, v) in fields: i...
mode = models.IntegerField(choices=list(API_STATUSES), default=1)
Given snippet: <|code_start|>class Key(models.Model): ''' API key to be handed out to Apis ''' user = models.OneToOneField(User, null=True, blank=True, related_name='api_key') key = models.CharField(max_length=32, db_index=True) email = models.EmailField(unique=True) alternate_email = m...
push_key.delay(self)
Predict the next line for this snippet: <|code_start|> LOG_PATH = getattr(settings, 'LOCKSMITH_LOG_PATH', '/var/log/nginx/access.log') LOG_REGEX = getattr( settings, 'LOCKSMITH_LOG_REGEX', r'.*\[(?P<date>\d{2}/\w{3}/\d{4}):\d{2}:\d{2}:\d{2} \+\d{4}\]\s*"(GET|POST) (?P<endpoint>[/\w\.]*)\?[^"]*apikey=(?P<api...
total_submitted = submit_report(
Next line prediction: <|code_start|> ReplicatedApiNames = getattr(settings, 'LOCKSMITH_REPLICATED_APIS', []) @task(max_retries=5) def push_key(key, replicate_too=True): if replicate_too: for kps in key.pub_statuses.filter(api__push_enabled=True): if kps.api.name in ReplicatedApiNames: ...
apicall(endpoint, kps.api.signing_key, api=kps.api.name,
Here is a snippet: <|code_start|> ReplicatedApiNames = getattr(settings, 'LOCKSMITH_REPLICATED_APIS', []) @task(max_retries=5) def push_key(key, replicate_too=True): if replicate_too: for kps in key.pub_statuses.filter(api__push_enabled=True): if kps.api.name in ReplicatedApiNames: ...
endpoints = {UNPUBLISHED: 'create_key/', NEEDS_UPDATE: 'update_key/'}
Using the snippet: <|code_start|> ReplicatedApiNames = getattr(settings, 'LOCKSMITH_REPLICATED_APIS', []) @task(max_retries=5) def push_key(key, replicate_too=True): if replicate_too: for kps in key.pub_statuses.filter(api__push_enabled=True): if kps.api.name in ReplicatedApiNames: ...
dirty = key.pub_statuses.exclude(status=PUBLISHED).filter(
Here is a snippet: <|code_start|> ReplicatedApiNames = getattr(settings, 'LOCKSMITH_REPLICATED_APIS', []) @task(max_retries=5) def push_key(key, replicate_too=True): if replicate_too: for kps in key.pub_statuses.filter(api__push_enabled=True): if kps.api.name in ReplicatedApiNames: ...
endpoints = {UNPUBLISHED: 'create_key/', NEEDS_UPDATE: 'update_key/'}
Based on the snippet: <|code_start|> class Command(BaseCommand): help = "Push a given day's logs up to the analytics hub" args = '[date:YYYY-MM-DD]' requires_model_validation = False def handle(self, date=None, *args, **options): if not date: # set date to yesterday if not passed in...
apicall(endpoint, settings.LOCKSMITH_SIGNING_KEY,
Given snippet: <|code_start|> class Command(BaseCommand): help = "Push a given day's logs up to the analytics hub" args = '[date:YYYY-MM-DD]' requires_model_validation = False def handle(self, date=None, *args, **options): if not date: # set date to yesterday if not passed in ...
results = db.logs.group(['key', 'method'],
Next line prediction: <|code_start|> QS_PARAM = getattr(settings, 'LOCKSMITH_QS_PARAM', 'apikey') HTTP_HEADER = getattr(settings, 'LOCKSMITH_HTTP_HEADER', 'HTTP_X_APIKEY') class APIKeyMiddleware(object): def process_request(self, request): key = request.GET.get(QS_PARAM, None) or request.META.get(HTTP_HEAD...
request.apikey = ApiKey.objects.get(key=key)
Using the snippet: <|code_start|>MODEL = getattr(settings, 'LOCKSMITH_STATS_MODEL', 'LogEntry') DATE_FIELD = getattr(settings, 'LOCKSMITH_STATS_DATE_FIELD', 'timestamp') ENDPOINT_FIELD = getattr(settings, 'LOCKSMITH_STATS_ENDPOINT_FIELD', 'method') USER_FIELD = getattr(settings, 'LOCKSMITH_STATS_USER_FIELD', 'caller_ke...
apicall(endpoint, settings.LOCKSMITH_SIGNING_KEY,
Given snippet: <|code_start|> def verify_signature(post): return get_signature(post, settings.LOCKSMITH_SIGNING_KEY) == post['signature'] @require_POST @csrf_exempt def create_key(request): if not verify_signature(request.POST): return HttpResponseBadRequest('bad signature') <|code_end|> , continue by ...
db.keys.insert({'_id':request.POST['key'],
Continue the code snippet: <|code_start|> class ApiKey(models.Model): key = models.CharField(max_length=32, primary_key=True) email = models.EmailField('Email Address') <|code_end|> . Use current file imports: import datetime from django.db import models from locksmith.common import KEY_STATUSES and context (...
status = models.CharField(max_length=1, choices=KEY_STATUSES, default='U')
Predict the next line for this snippet: <|code_start|> class ApiAdmin(admin.ModelAdmin): list_display = ('name', 'url', 'push_enabled') admin.site.register(Api, ApiAdmin) class KeyAdmin(admin.ModelAdmin): list_display = ('key', 'status', 'email', 'name', 'org_name', 'org_url') search_fields = ('key', 'ema...
admin.site.register(Key, KeyAdmin)
Next line prediction: <|code_start|> try: SIGNING_KEY = settings.LOCKSMITH_SIGNING_KEY API_NAME = settings.LOCKSMITH_API_NAME ENDPOINT = settings.LOCKSMITH_HUB_URL.replace('analytics', 'accounts') + 'checkkey/' except: SIGNING_KEY = "" API_NAME = "" ENDPOINT = "" def check_key(key, signing_key=...
apicall(endpoint, signing_key,
Continue the code snippet: <|code_start|> def verify_signature(post): return get_signature(post, settings.LOCKSMITH_SIGNING_KEY) == post['signature'] @csrf_exempt @require_POST def create_key(request): if not verify_signature(request.POST): return HttpResponseBadRequest('bad signature') <|code_end|> . ...
ApiKey.objects.create(key=request.POST['key'],
Predict the next line for this snippet: <|code_start|> QS_PARAM = getattr(settings, 'LOCKSMITH_QS_PARAM', 'apikey') HTTP_HEADER = getattr(settings, 'LOCKSMITH_HTTP_HEADER', 'HTTP_X_APIKEY') class APIKeyMiddleware(object): def process_request(self, request): key = request.GET.get(QS_PARAM, None) or request....
apikey = db.keys.find_one({'_id':key})
Given the following code snippet before the placeholder: <|code_start|> """Rescale radius of gyration of structure to 1""" rg = radius_of_gyration(self) for i, point in enumerate(self.points): if point != 0: x, y, z = point.pos self.points[i].pos = (x/rg, y/rg, z/rg) class Point(object): """Point in 3...
tracker = Tracker("Identifying loci", size)
Here is a snippet: <|code_start|> for structure in structures: new_points = np.zeros(structure.chrom.getLength(), dtype=object) for i, gen_coord in enumerate(consensus): abs_index = structure.chrom.getAbsoluteIndex(gen_coord) pos = structure.points[abs_index - structure.offset].pos new_points[abs_index - s...
expected = get_expected(contactMat)
Predict the next line for this snippet: <|code_start|>sys.path.append("..") def matFromDixon(path, chrom): """Creates contact matrix from Dixon tsv data""" numBins = chrom.getLength() mat = np.zeros((numBins, numBins)) <|code_end|> with the help of current file imports: import sys import data_tools as dt import s...
tracker = Tracker("Reading " + path, chrom.size)
Based on the snippet: <|code_start|> if bin1 > bin2: row = bin1 col = bin2 else: row = bin1 col = bin2 mat[row, col] += 1 tracker.increment() infile.close() return mat def plotLevels(mat): smoothingFactors = [1, 2, 3, 8, 33] #these smoothing factors were selected to demonstr...
chrom = ChromParameters(minPos, maxPos, res, name, size)
Next line prediction: <|code_start|>sys.path.append("..") def matFromDixon(path, chrom): """Creates contact matrix from Dixon tsv data""" numBins = chrom.getLength() mat = np.zeros((numBins, numBins)) <|code_end|> . Use current file imports: (import sys import heatmap as hm import simple_tad as tad import numpy as...
tracker = Tracker("Reading " + path, chrom.size)
Predict the next line for this snippet: <|code_start|>from __future__ import print_function batch_size = 128 nb_epoch = 100 nb_classes = 19 * 19 # One class for each position on the board go_board_rows, go_board_cols = 19, 19 # input dimensions of go board nb_filters = 32 # number of convolutional filters to use ...
processor = SevenPlaneProcessor()
Here is a snippet: <|code_start|>from __future__ import print_function parser = argparse.ArgumentParser() parser.add_argument('--bot-name', default='new_bot') parser.add_argument('--epochs', type=int, default=5) parser.add_argument('--sample-size', type=int, default=1000) args = parser.parse_args() here = os.path...
processor = SevenPlaneProcessor(use_generator=True)
Predict the next line after this snippet: <|code_start|> class ModelTestCase(unittest.TestCase): def test_all_empty_points(self): board = goboard.from_string(''' .b. bb. .ww ''') <|code_end|> using the current file's imports: import unittest import six from ...
empty_points = model.all_empty_points(board)
Given the following code snippet before the placeholder: <|code_start|> class CommandTestCase(unittest.TestCase): def test_parse(self): command_string = 'play white D4' <|code_end|> , predict the next line using imports from the current file: import unittest from betago.gtp import command and context in...
expected = command.Command(
Next line prediction: <|code_start|>from __future__ import print_function argparser = argparse.ArgumentParser() argparser.add_argument('handicap', type=int, nargs=1) argparser.add_argument('output_sgf', nargs='?', default='output.sgf') args = argparser.parse_args() <|code_end|> . Use current file imports: (import y...
processor = SevenPlaneProcessor()
Continue the code snippet: <|code_start|># This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. from __future__ import print_function from __future__ import absolute_import c...
index = KGSIndex(data_directory=self.data_dir)
Based on the snippet: <|code_start|> class ResponseTestCase(unittest.TestCase): def setUp(self): self.cmd = command.Command(None, 'genmove', ('black',)) self.cmd_with_sequence = command.Command(99, 'genmove', ('black',)) def test_serialize(self): <|code_end|> , predict the immediate next line...
resp = response.success('D4')
Predict the next line for this snippet: <|code_start|>"""Tests for sgf_properties.py.""" class SgfPropertiesTestCase(unittest.TestCase): def test_interpret_simpletext(self): def interpret(s, encoding): <|code_end|> with the help of current file imports: import unittest from textwrap import dedent from...
context = sgf_properties._Context(19, encoding)
Using the snippet: <|code_start|>from __future__ import print_function batch_size = 128 nb_epoch = 20 nb_classes = 19 * 19 # One class for each position on the board go_board_rows, go_board_cols = 19, 19 # input dimensions of go board nb_filters = 32 # number of convolutional filters to use nb_pool = 2 # size of ...
processor = SevenPlaneProcessor()
Predict the next line after this snippet: <|code_start|> class GTPCoordinateTest(unittest.TestCase): def test_coords_to_gtp_position(self): self.assertEqual('A1', coords_to_gtp_position((0, 0))) self.assertEqual('J3', coords_to_gtp_position((2, 8))) self.assertEqual('B15', coords_to_gtp_po...
self.assertEqual((0, 0), gtp_position_to_coords('A1'))
Next line prediction: <|code_start|>from __future__ import print_function argparser = argparse.ArgumentParser() argparser.add_argument('handicap', type=int, nargs=1) argparser.add_argument('output_sgf', nargs='?', default='output.sgf') args = argparser.parse_args() <|code_end|> . Use current file imports: (import y...
processor = SevenPlaneProcessor()
Given the code snippet: <|code_start|> class ScoringTestCase(unittest.TestCase): def test_identify_territory(self): board = goboard.from_string(''' ...b..w.. ...b..w.. bbbb..w.. wwwww.www wwbbw..w. wb.bbwww. wbbbb.... ...
territory = scoring.evaluate_territory(board)
Continue the code snippet: <|code_start|> """ Selects the best `elite_size` results according to `fitness()` from the current experiment. Uniformly samples one of them as a parent, and perturbs it using the experiment's samplers. Note that in order to change parent, you should call experiment sampl...
fitness = leq
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3 try: except ImportError: try: except ImportError: <|code_end|> with the help of current file imports: import os import random import ujson as json import json import cPickle as pk import pickle as pk from time import tim...
class HyperBand(Experiment):
Using the snippet: <|code_start|>#!/usr/bin/env python3 try: except ImportError: try: except ImportError: class HyperBand(Experiment): """ HyperBand implementation, based on http://people.eecs.berkeley.edu/~kjamieson/hyperband.html """ def __init__(self, name, params, num_iter, eta=None, comp...
comparator = leq
Given the code snippet: <|code_start|> self.s0 = val[:, 1] self._initial_state = val def get_solution( self, t: ndarray, stacked: bool = True, with_keys: bool = False ) -> Union[Dict, ndarray]: """Calculate solution of dynamics. Arguments --------- t ...
c = (self.alpha - self.u0 * self.beta) * invert(self.gamma - self.beta)
Given the following code snippet before the placeholder: <|code_start|> data.obs.keys(), data.var.keys(), data.obsm.keys(), data.varm.keys(), data.uns.keys(), data.layers.keys(), ] if hasattr(data, "obsp") and hasattr(data, "varp"):...
logg.warn(f"'{key}' found multiple times in {', '.join(s_key)}.")
Using the snippet: <|code_start|> s_key = [s for (s, d_key) in zip(s_keys, d_keys) if key in d_key] if len(s_key) == 0: raise ValueError(f"'{key}' not found in any of {', '.join(s_keys)}.") if len(s_key) > 1: logg.warn(f"'{key}' found multiple times in ...
if np.sum(num_cats) == 1:
Based on the snippet: <|code_start|> """\ Score cell cycle genes. Calculates scores and assigns a cell cycle phase (G1, S, G2M) using the list of cell cycle genes defined in Tirosh et al, 2015 (https://doi.org/10.1126/science.aad0501). Parameters ---------- adata The annotated data ...
logg.info("calculating cell cycle phase")
Predict the next line for this snippet: <|code_start|> neighs = NearestNeighbors(n_neighbors=100) neighs.fit(adata.obsm[f"X_{basis_constraint}"]) basis_graph = neighs.kneighbors_graph(mode="connectivity") > 0 graph = graph.multiply(basis_graph) if self_transitions: confidenc...
get_connectivities(
Predict the next line for this snippet: <|code_start|> graph_neg = adata.obsp[f"{vkey}_graph_neg"] else: graph = csr_matrix(adata.uns[f"{vkey}_graph"]).copy() if f"{vkey}_graph_neg" in adata.uns.keys(): graph_neg = adata.uns[f"{vkey}_graph_neg"] if bas...
direct_neighbors = get_neighs(adata, "distances") > 0
Given the following code snippet before the placeholder: <|code_start|> if graph_neg is not None: graph_neg = adata.uns[f"{vkey}_graph_neg"] if use_negative_cosines: T -= np.expm1(-graph_neg * scale) else: T += np.expm1(graph_neg * scale) T.data += 1 #...
T = normalize(T)
Predict the next line after this snippet: <|code_start|> If `None`, split into :paramref:`n_jobs` chunks. unit Unit of the progress bar. as_array Whether to convert the results not :class:`numpy.ndarray`. use_ixs Whether to pass indices to the callback. backend Whi...
logg.warn(
Given the code snippet: <|code_start|> else: trimmer = csr_matrix( (normalized_data <= bound[0]) | (normalized_data >= bound[1]) ).astype(bool) return [trimmer.getnnz(axis=0)] + [ trimmer.multiply(data_mat).tocsr() for data_mat in data ] d...
_xx = prod_sum(x, x, axis=0)
Predict the next line after this snippet: <|code_start|> if constrain_ratio is None: self.constrain_ratio = [-np.inf, np.inf] elif len(constrain_ratio) == 1: self.constrain_ratio = [-np.inf, constrain_ratio] else: self.constrain_ratio = constrain_ratio de...
normalized_data = np.sum(
Predict the next line after this snippet: <|code_start|> if isinstance(groups, str) and groups == "all": if color is None: color = default_color(adata) if is_categorical(adata, color): vc = adata.obs[color].value_counts() groups = [[c] for c in vc[vc > 0].index] ...
logg.warn("Cannot specify `ax` when plotting multiple panels.")
Continue the code snippet: <|code_start|> adata = AnnData(np.stack([x, y]).T) # restore old conventions add_assignments = kwargs.pop("show_assignments", add_assignments) add_linfit = kwargs.pop("show_linear_fit", add_linfit) add_polyfit = kwargs.pop("show_polyfit", add_polyfit) add_density =...
kwargs["rasterized"] = settings._vector_friendly
Continue the code snippet: <|code_start|> ) zorder -= 1 # if color is in {'ascending', 'descending'} elif isinstance(color, str): if color == "ascending": color = np.linspace(0, 1, len(x)) elif color == "descendi...
c = get_connectivities(adata, n_neighbors=n_neighbors).dot(c)
Based on the snippet: <|code_start|>"""Logging and Profiling """ _VERBOSITY_LEVELS_FROM_STRINGS = {"error": 0, "warn": 1, "info": 2, "hint": 3} def info(*args, **kwargs): return msg(*args, v="info", **kwargs) def error(*args, **kwargs): args = ("Error:",) + args return msg(*args, v="error", **kwargs...
if isinstance(settings.verbosity, str):
Given the code snippet: <|code_start|>""" Mural views =========== This module defines views that will be used to browse murals. """ mural_blueprint = Blueprint('mural', __name__, url_prefix='/') @mural_blueprint.route('/', methods=['GET', ]) def entrypoint(): """ The main entrypoint of our mural...
years = next(zip(*Mural.query.order_by(Mural.year).distinct().values(Mural.year)), [])
Predict the next line after this snippet: <|code_start|>def _set_data_field(fields, args): if 'location' not in fields and 'copy_from' not in fields: fields['data'] = utils.get_data_file(args) @utils.arg('image', metavar='<IMAGE>', help='Name or ID of image to describe.') @utils.arg('--human-readable', ac...
body = progressbar.VerboseIteratorWrapper(body, len(body))
Given the following code snippet before the placeholder: <|code_start|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # ...
@utils.arg('--name', metavar='<NAME>',
Continue the code snippet: <|code_start|> UPDATE_PARAMS = glanceclient.v1.images.UPDATE_PARAMS fields = dict(filter(lambda x: x[0] in UPDATE_PARAMS, fields.items())) if image.status == 'queued': _set_data_field(fields, args) if args.progress: filesize = utils.get_file_size(field...
raise exc.CommandError(msg)
Continue the code snippet: <|code_start|> body = self.client.patch(url, json=json).json() if response_key is not None: return self.resource_class(self, body[response_key]) else: return self.resource_class(self, body) def _delete(self, url): """Delete an object...
msg = _("No %(name)s matching %(args)s.") % {
Predict the next line for this snippet: <|code_start|> return self.resource_class(self, body) def _delete(self, url): """Delete an object. :param url: a partial URL, e.g., '/servers/my-server' """ return self.client.delete(url) class ManagerWithFind(BaseManager, metacl...
raise exceptions.NotFound(msg)
Given snippet: <|code_start|> "aligned with Heat resource types " "whenever possible: http://docs." "openstack.org/developer/heat/" "template_guide/openstack.html", ...
self.api = utils.FakeAPI(data_fixtures)
Using the snippet: <|code_start|> "type": "string" }, "required": { "$ref": "#/definitions/stringArray" }, "properties": { "$ref": "#/definitions/property" ...
self.controller = base.BaseController(self.api, self.schema_api,
Given the code snippet: <|code_start|> }, "self": { "type": "string" }, "required": { "$ref": "#/definitions/stringArray" }, "properties": { ...
self.api = utils.FakeAPI(data_fixtures)
Based on the snippet: <|code_start|> }, "required": { "$ref": "#/definitions/stringArray" }, "properties": { "$ref": "#/definitions/property" }, "schema"...
metadefs.ObjectController)
Continue the code snippet: <|code_start|> # now try to get entity as uuid try: tmp_id = encodeutils.safe_decode(name_or_id) if uuidutils.is_uuid_like(tmp_id): return manager.get(tmp_id) except (TypeError, ValueError, exceptions.NotFound): pass # for str id which is n...
msg = _("No %(name)s with a name or "
Predict the next line for this snippet: <|code_start|># # THIS MODULE IS DEPRECATED # # Please refer to # https://etherpad.openstack.org/p/kilo-glanceclient-library-proposals for # the discussion leading to this deprecation. # # We recommend checking out the python-openstacksdk project # (https://launchpad.net/python-o...
except (TypeError, ValueError, exceptions.NotFound):
Using the snippet: <|code_start|> HTTPSConnection = http.client.HTTPSConnection Connection = SSL.Connection def verify_callback(host=None): """Provide wrapper for do_verify_callback. We use a partial around the 'real' verify_callback function so that we can stash the host value without holding a...
raise exc.SSLCertificateError(msg)
Continue the code snippet: <|code_start|># Copyright 2022 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
self.info_controller = info.Controller(self.fake_client, None)
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
class HttpHeadersTest(base.ClientTestBase):
Next line prediction: <|code_start|> '/v2/images/{image}/tags/{tag_value}'.format(image=IMAGE, tag_value=TAG): { 'DELETE': ( {}, None, ), 'PUT': ( {}, { 'image_id': IMAGE, 'tag_value': TAG } ),...
self.controller = base.BaseController(self.api, self.schema_api,
Given the following code snippet before the placeholder: <|code_start|> data_fixtures = { '/v2/images/{image}/tags/{tag_value}'.format(image=IMAGE, tag_value=TAG): { 'DELETE': ( {}, None, ), 'PUT': ( {}, { 'image_id': IMAGE, ...
self.api = utils.FakeAPI(data_fixtures)
Predict the next line after this snippet: <|code_start|> 'DELETE': ( {}, None, ), 'PUT': ( {}, { 'image_id': IMAGE, 'tag_value': TAG } ), } } schema_fixtures = { 'tag': { 'GET': ( ...
image_tags.Controller)
Based on the snippet: <|code_start|> # is required because the test_shell.do_xxx(gc, args) methods # expects the args to be attributes of an object. If passed as # dict directly, it throws an AttributeError. class Args(object): def __init__(self, entries): self...
exc.CommunicationError, self.run_command, 'image-list')
Using the snippet: <|code_start|> '/v1/images/70aa106f-3750-4d7c-a5ce-0a535ac08d0a': { 'HEAD': ( { 'x-image-meta-id': '70aa106f-3750-4d7c-a5ce-0a535ac08d0a', 'x-image-meta-status': 'deleted' }, None ) } } class ShellInvalidEndp...
self.shell = shell.OpenStackImagesShell()
Predict the next line after this snippet: <|code_start|> 'x-image-meta-disk_format': 'ami', }, None ) }, '/v1/images/detail?limit=20&name=70aa106f-3750-4d7c-a5ce-0a535ac08d0a': { 'GET': ( {}, {'images': [ { ...
class ShellInvalidEndpointandParameterTest(utils.TestCase):
Given snippet: <|code_start|> { "status": "CURRENT", "id": "v2.3", "links": [ { "href": "http://10.229.45.145:9292/v2/", "rel": "self" } ...
self.api = utils.FakeAPI(fixtures)
Given the code snippet: <|code_start|># a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, ...
return http.HTTPClient(self.endpoint, token=self.token)
Using the snippet: <|code_start|> def test_http_json(self): data = {"test": "json_request"} path = '/v1/images' text = 'OK' self.mock.post(self.endpoint + path, text=text) headers = {"test": u'chunked_request'} resp, body = self.client.post(path, headers=headers, dat...
fake = utils.FakeResponse(headers, io.StringIO(response))
Next line prediction: <|code_start|> ), }, } schema_fixtures = { 'task': { 'GET': ( {}, { 'name': 'task', 'properties': { 'id': {}, 'type': {}, 'status': {}, 'i...
self.controller = base.BaseController(self.api, self.schema_api,
Given snippet: <|code_start|> }, ]}, ), }, } schema_fixtures = { 'task': { 'GET': ( {}, { 'name': 'task', 'properties': { 'id': {}, 'type': {}, 'status'...
self.api = utils.FakeAPI(fixtures)
Given snippet: <|code_start|># Copyright 2013 OpenStack Foundation. # Copyright 2013 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http...
'/v2/tasks?limit=%d' % tasks.DEFAULT_PAGE_SIZE: {
Given the following code snippet before the placeholder: <|code_start|> "type": "string", "readOnly": True, "description": "Date and time of namespace creation ", "format": "date-time" }, ...
self.controller = base.BaseController(self.api, self.schema_api,
Next line prediction: <|code_start|> }, "created_at": { "type": "string", "readOnly": True, "description": "Date and time of namespace creation ", "format": "date-time" ...
self.api = utils.FakeAPI(data_fixtures)
Predict the next line for this snippet: <|code_start|># # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express...
__, version = utils.strip_version(endpoint)
Given snippet: <|code_start|># Copyright 2013 OpenStack Foundation # Copyright 2013 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http:...
@utils.memoized_property
Predict the next line after this snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
base_class=schemas.SchemaBasedModel)
Given the code snippet: <|code_start|> The requests library performs SSL certificate validation, however there is still a need to check that the glance client is properly integrated with requests so that cert validation actually happens. """ def setUp(self): # Rather than spinning up a n...
except exc.CommunicationError as e:
Continue the code snippet: <|code_start|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
out = exc.from_response(mock_resp)