text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(length): """Generates random and valid card number which is returned as a string."""
if not isinstance(length, int) or length < 2: raise TypeError('length must be a positive integer greater than 1.') # first digit cannot be 0 digits = [random.randint(1, 9)] for i in range(length-2): digits.append(random.randint(0, 9)) digits.append(get_check_digit(''.join(map(str, digits)))) return ''.join(map(str, digits))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_backend(): """Get backend."""
backend = getattr(settings, 'SIMDITOR_IMAGE_BACKEND', None) if backend == 'pillow': from simditor.image import pillow_backend as backend else: from simditor.image import dummy_backend as backend return backend
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _rspiral(width, height): """Reversed spiral generator. Parameters width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points. """
x0 = 0 y0 = 0 x1 = width - 1 y1 = height - 1 while x0 < x1 and y0 < y1: for x in range(x0, x1): yield x, y0 for y in range(y0, y1): yield x1, y for x in range(x1, x0, -1): yield x, y1 for y in range(y1, y0, -1): yield x0, y x0 += 1 y0 += 1 x1 -= 1 y1 -= 1 if x0 == x1: for y in range(y0, y1 + 1): yield x0, y elif y0 == y1: for x in range(x0, x1 + 1): yield x, y0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _spiral(width, height): """Spiral generator. Parameters width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points. """
if width == 1: for y in range(height - 1, -1, -1): yield 0, y return if height == 1: for x in range(width - 1, -1, -1): yield x, 0 return if width <= height: x0 = width // 2 if width % 2: for y in range(height - 1 - x0, x0 - 1, -1): yield x0, y x0 -= 1 y0 = x0 else: y0 = height // 2 if height % 2: for x in range(width - 1 - y0, y0 - 1, -1): yield x, y0 y0 -= 1 x0 = y0 while x0 >= 0: x1 = width - x0 - 1 y1 = height - y0 - 1 for y in range(y0 + 1, y1): yield x0, y for x in range(x0, x1): yield x, y1 for y in range(y1, y0, -1): yield x1, y for x in range(x1, x0 - 1, -1): yield x, y0 x0 -= 1 y0 -= 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_point_in_block(cls, x, y, block_idx, block_size): """Get point coordinates in next block. Parameters x : `int` X coordinate in current block. y : `int` Y coordinate in current block. block_index : `int` Current block index in next block. block_size : `int` Current block size. Raises ------ IndexError If block index is out of range. Returns ------- (`int`, `int`) Point coordinates. """
if block_idx == 0: return y, x if block_idx == 1: return x, y + block_size if block_idx == 2: return x + block_size, y + block_size if block_idx == 3: x, y = block_size - 1 - y, block_size - 1 - x return x + block_size, y raise IndexError('block index out of range: %d' % block_idx)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_point(cls, idx, size): """Get curve point coordinates by index. Parameters idx : `int` Point index. size : `int` Curve size. Returns ------- (`int`, `int`) Point coordinates. """
x, y = cls.POSITION[idx % 4] idx //= 4 block_size = 2 while block_size < size: block_idx = idx % 4 x, y = cls.get_point_in_block(x, y, block_idx, block_size) idx //= 4 block_size *= 2 return x, y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __recur_to_dict(forlist, data_dict, res): """Recursive function that fills up the dictionary """
# First we go through all attrs from the ForList and add respective # keys on the dict. for a in forlist.attrs: a_list = a.split('.') if len(a_list) == 1: res = data_dict[a_list[0]] return res if a_list[0] in data_dict: tmp = res for i in a_list[1:-1]: if not i in tmp: tmp[i] = {} tmp = tmp[i] if len(a_list) == 1: tmp[a_list[0]] = data_dict[a_list[0]] else: tmp[a_list[-1]] = reduce( getattr, a_list[1:], data_dict[a_list[0]] ) # Then create a list for all children, # modify the datadict to fit the new child # and call myself for c in forlist.childs: it = c.name.split('.') res[it[-1]] = [] for i, val in enumerate( reduce(getattr, it[1:], data_dict[it[0]]) ): new_data_dict = {c.var_from: val} if len(res[it[-1]]) <= i: res[it[-1]].append({}) res[it[-1]] = ForList.__recur_to_dict( c, new_data_dict, res[it[-1]][i] ) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(for_lists, global_vars, data_dict): """ Construct a dict object from a list of ForList object :param for_lists: list of for_list :param global_vars: list of global vars to add :param data_dict: data from an orm-like object (with dot notation) :return: a dict representation of the ForList objects """
res = {} # The first level is a little bit special # Manage global variables for a in global_vars: a_list = a.split('.') tmp = res for i in a_list[:-1]: if not i in tmp: tmp[i] = {} tmp = tmp[i] tmp[a_list[-1]] = reduce(getattr, a_list[1:], data_dict[a_list[0]]) # Then manage for lists recursively for for_list in for_lists: it = for_list.name.split('.') tmp = res for i in it[:-1]: if not i in tmp: tmp[i] = {} tmp = tmp[i] if not it[-1] in tmp: tmp[it[-1]] = [] tmp = tmp[it[-1]] if not it[0] in data_dict: continue if len(it) == 1: loop = enumerate(data_dict[it[0]]) else: loop = enumerate(reduce(getattr, it[-1:], data_dict[it[0]])) for i, val in loop: new_data_dict = {for_list.var_from: val} # We append a new dict only if we need if len(tmp) <= i: tmp.append({}) # Call myself with new context, and get result tmp[i] = ForList.__recur_to_dict( for_list, new_data_dict, tmp[i] ) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL): """ Nothing hilariously hidden here, logs a user out. Strip this out if your application already has hooks to handle this. """
django_logout(request) return HttpResponseRedirect(request.build_absolute_uri(redirect_url))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def begin_auth(request): """The view function that initiates the entire handshake. For the most part, this is 100% drag and drop. """
# Instantiate Twython with the first leg of our trip. twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) # Request an authorization url to send the user to... callback_url = request.build_absolute_uri(reverse('twython_django_oauth.views.thanks')) auth_props = twitter.get_authentication_tokens(callback_url) # Then send them over there, durh. request.session['request_token'] = auth_props request.session['next_url'] = request.GET.get('next',None) return HttpResponseRedirect(auth_props['auth_url'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL): """A user gets redirected here after hitting Twitter and authorizing your app to use their data. This is the view that stores the tokens you want for querying data. Pay attention to this. """
# Now that we've got the magic tokens back from Twitter, we need to exchange # for permanent ones and store them... oauth_token = request.session['request_token']['oauth_token'] oauth_token_secret = request.session['request_token']['oauth_token_secret'] twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, oauth_token, oauth_token_secret) # Retrieve the tokens we want... authorized_tokens = twitter.get_authorized_tokens(request.GET['oauth_verifier']) # If they already exist, grab them, login and redirect to a page displaying stuff. try: user = User.objects.get(username=authorized_tokens['screen_name']) except User.DoesNotExist: # We mock a creation here; no email, password is just the token, etc. user = User.objects.create_user(authorized_tokens['screen_name'], "[email protected]", authorized_tokens['oauth_token_secret']) profile = TwitterProfile() profile.user = user profile.oauth_token = authorized_tokens['oauth_token'] profile.oauth_secret = authorized_tokens['oauth_token_secret'] profile.save() user = authenticate( username=authorized_tokens['screen_name'], password=authorized_tokens['oauth_token_secret'] ) login(request, user) redirect_url = request.session.get('next_url', redirect_url) HttpResponseRedirect(redirect_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _imgdata(self, width, height, state_size=None, start='', dataset=''): """Generate image pixels. Parameters width : `int` Image width. height : `int` Image height. state_size : `int` or `None`, optional State size to use for generation (default: `None`). start : `str`, optional Initial state (default: ''). dataset : `str`, optional Dataset key prefix (default: ''). Raises ------ RuntimeError If generator is empty. Returns ------- `generator` of `int` Pixel generator. """
size = width * height if size > 0 and start: yield state_to_pixel(start) size -= 1 while size > 0: prev_size = size pixels = self.generate(state_size, start, dataset) pixels = islice(pixels, 0, size) for pixel in pixels: yield state_to_pixel(pixel) size -= 1 if prev_size == size: if start: yield from repeat(state_to_pixel(start), size) else: raise RuntimeError('empty generator')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_imgdata(img, data, tr, x=0, y=0): """Write image data. Parameters img : `PIL.Image.Image` Image. data : `iterable` of `int` Image data. tr : `markovchain.image.traversal.Traversal` Image traversal. x : `int` X offset. y : `int` Y offset. """
for pixel, (x1, y1) in zip(data, tr): img.putpixel((x + x1, y + y1), pixel) return img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _channel(self, width, height, state_sizes, start_level, start_image, dataset): """Generate a channel. Parameters width : `int` Image width. height : `int` Image height. state_sizes : `list` of (`int` or `None`) Level state sizes. start_level : `int` Initial level. start_image : `PIL.Image` or `None` Initial level image. dataset : `str` Dataset key prefix. Returns ------- `PIL.Image` Generated image. """
ret = start_image for level, state_size in enumerate(state_sizes, start_level + 1): key = dataset + level_dataset(level) if start_image is not None: scale = self.scanner.level_scale[level - 1] width *= scale height *= scale ret = self.imgtype.create_channel(width, height) if start_image is None: tr = self.scanner.traversal[0](width, height, ends=False) data = self._imgdata(width, height, state_size, '', key) self._write_imgdata(ret, data, tr) else: tr = self.scanner.traversal[0]( start_image.size[0], start_image.size[1], ends=False ) for xy in tr: start = pixel_to_state(start_image.getpixel(xy)) data = self._imgdata(scale, scale, state_size, start, key) blk = self.scanner.traversal[level](scale, scale, False) x, y = xy x *= scale y *= scale self._write_imgdata(ret, data, blk, x, y) start_image = ret return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ravel(parameter, random_state=None): """ Flatten a ``Parameter``. Parameters parameter: Parameter A ``Parameter`` object Returns ------- flatvalue: ndarray a flattened array of shape ``(prod(parameter.shape),)`` flatbounds: list a list of bound tuples of length ``prod(parameter.shape)`` """
flatvalue = np.ravel(parameter.rvs(random_state=random_state)) flatbounds = [parameter.bounds for _ in range(np.prod(parameter.shape, dtype=int))] return flatvalue, flatbounds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hstack(tup): """ Horizontally stack a sequence of value bounds pairs. Parameters tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: ndarray a horizontally concatenated array1d bounds: a list of Bounds """
vals, bounds = zip(*tup) stackvalue = np.hstack(vals) stackbounds = list(chain(*bounds)) return stackvalue, stackbounds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self, value): """ Check a value falls within a bound. Parameters value : scalar or ndarray value to test Returns ------- bool: If all values fall within bounds Example ------- True False True False """
if self.lower: if np.any(value < self.lower): return False if self.upper: if np.any(value > self.upper): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clip(self, value): """ Clip a value to a bound. Parameters value : scalar or ndarray value to clip Returns ------- scalar or ndarray : of the same shape as value, bit with each element clipped to fall within the specified bounds Example ------- 1.5 2 array([ 1. , 2. , 1.5]) array([ 1. , 3. , 1.5]) """
if not self.lower and not self.upper: return value return np.clip(value, self.lower, self.upper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rvs(self, random_state=None): r""" Draw a random value from this Parameter's distribution. If ``value`` was not initialised with a ``scipy.stats`` object, then the scalar/ndarray value is returned. Parameters random_state : None, int or RandomState, optional random seed Returns ------- ndarray : of size ``self.shape``, a random draw from the distribution, or ``self.value`` if not initialised with a ``scipy.stats`` object. Note ---- Random draws are *clipped* to the bounds, and so it is up to the user to input a sensible sampling distribution! """
# No sampling distibution if self.dist is None: return self.value # Unconstrained samples rs = check_random_state(random_state) samples = self.dist.rvs(size=self.shape, random_state=rs) # Bound the samples samples = self.bounds.clip(samples) return samples
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_missing_trees(self, path, root_tree): """ Creates missing ``Tree`` objects for the given path. :param path: path given as a string. It may be a path to a file node (i.e. ``foo/bar/baz.txt``) or directory path - in that case it must end with slash (i.e. ``foo/bar/``). :param root_tree: ``dulwich.objects.Tree`` object from which we start traversing (should be commit's root tree) """
dirpath = posixpath.split(path)[0] dirs = dirpath.split('/') if not dirs or dirs == ['']: return [] def get_tree_for_dir(tree, dirname): for name, mode, id in tree.iteritems(): if name == dirname: obj = self.repository._repo[id] if isinstance(obj, objects.Tree): return obj else: raise RepositoryError("Cannot create directory %s " "at tree %s as path is occupied and is not a " "Tree" % (dirname, tree)) return None trees = [] parent = root_tree for dirname in dirs: tree = get_tree_for_dir(parent, dirname) if tree is None: tree = objects.Tree() dirmode = 040000 parent.add(dirmode, dirname, tree.id) parent = tree # Always append tree trees.append(tree) return trees
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_list(x): """Convert a value to a list. Parameters x Value. Returns ------- `list` Examples -------- [0] [{'x': 0}] [0, 1, 4] [1, 2, 3] True """
if isinstance(x, list): return x if not isinstance(x, dict): try: return list(x) except TypeError: pass return [x]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill(xs, length, copy=False): """Convert a value to a list of specified length. If the input is too short, fill it with its last element. Parameters xs Input list or value. length : `int` Output list length. copy : `bool`, optional Deep copy the last element to fill the list (default: False). Returns ------- `list` Raises ------ ValueError If `xs` is empty and `length` > 0 Examples -------- [0, 0, 0] [0] [{'x': 0}, {'x': 1}, {'x': 1}, {'x': 1}] True True [{'x': 0}, {'x': 1}, {'x': 1}, {'x': 1}] False False """
if isinstance(xs, list) and len(xs) == length: return xs if length <= 0: return [] try: xs = list(islice(xs, 0, length)) if not xs: raise ValueError('empty input') except TypeError: xs = [xs] if len(xs) < length: if copy: last = xs[-1] xs.extend(deepcopy(last) for _ in range(length - len(xs))) else: xs.extend(islice(repeat(xs[-1]), 0, length - len(xs))) return xs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def int_enum(cls, val): """Get int enum value. Parameters cls : `type` Int enum class. val : `int` or `str` Name or value. Returns ------- `IntEnum` Raises ------ ValueError """
if isinstance(val, str): val = val.upper() try: return getattr(cls, val) except AttributeError: raise ValueError('{0}.{1}'.format(cls, val)) return cls(val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(obj, cls, default_factory): """Create or load an object if necessary. Parameters obj : `object` or `dict` or `None` cls : `type` default_factory : `function` Returns ------- `object` """
if obj is None: return default_factory() if isinstance(obj, dict): return cls.load(obj) return obj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def truncate(string, maxlen, end=True): """Truncate a string. Parameters string : `str` String to truncate. maxlen : `int` Maximum string length. end : `boolean`, optional Remove characters from the end (default: `True`). Raises ------ ValueError If `maxlen` <= 3. Returns ------- `str` Truncated string. Examples -------- 'str' """
if maxlen <= 3: raise ValueError('maxlen <= 3') if len(string) <= maxlen: return string if end: return string[:maxlen - 3] + '...' return '...' + string[3 - maxlen:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_class(cls, *args): """Add classes to the group. Parameters *args : `type` Classes to add. """
for cls2 in args: cls.classes[cls2.__name__] = cls2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_class(cls, *args): """Remove classes from the group. Parameters *args : `type` Classes to remove. """
for cls2 in args: try: del cls.classes[cls2.__name__] except KeyError: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(cls, data): """Create an object from JSON data. Parameters data : `dict` JSON data. Returns `object` Created object. Raises ------ KeyError If `data` does not have the '__class__' key or the necessary class is not in the class group. """
ret = cls.classes[data['__class__']] data_cls = data['__class__'] del data['__class__'] try: ret = ret(**data) finally: data['__class__'] = data_cls return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_oauth_client(self, consumer_key, consumer_secret): """Sets the oauth_client attribute """
self.oauth_client = oauth1.Client(consumer_key, consumer_secret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_request(self, method, url, body=''): """Prepare the request body and headers :returns: headers of the signed request """
headers = { 'Content-type': 'application/json', } # Note: we don't pass body to sign() since it's only for bodies that # are form-urlencoded. Similarly, we don't care about the body that # sign() returns. uri, signed_headers, signed_body = self.oauth_client.sign( url, http_method=method, headers=headers) if body: if method == 'GET': body = urllib.urlencode(body) else: body = json.dumps(body) headers.update(signed_headers) return {"headers": headers, "data": body}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_error_reason(response): """Extract error reason from the response. It might be either the 'reason' or the entire response """
try: body = response.json() if body and 'reason' in body: return body['reason'] except ValueError: pass return response.content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch(self, method, url, data=None, expected_status_code=None): """Prepare the headers, encode data, call API and provide data it returns """
kwargs = self.prepare_request(method, url, data) log.debug(json.dumps(kwargs)) response = getattr(requests, method.lower())(url, **kwargs) log.debug(json.dumps(response.content)) if response.status_code >= 400: response.raise_for_status() if (expected_status_code and response.status_code != expected_status_code): raise NotExpectedStatusCode(self._get_error_reason(response)) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_json(self, method, url, data=None, expected_status_code=None): """Return json decoded data from fetch """
return self.fetch(method, url, data, expected_status_code).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def structured_minimizer(minimizer): r""" Allow an optimizer to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `btypes.py`, and can accept nested sequences of *any* structure of these objects to optimise! It can also optionally evaluate *random starts* (i.e. random starting candidates) if the parameter objects have been initialised with distributions. For this, two additional parameters are exposed in the :code:`minimizer` interface. Parameters fun : callable objective function that takes in arbitrary ndarrays, floats or nested sequences of these. parameters : (nested) sequences of Parameter objects Initial guess of the parameters of the objective function nstarts : int, optional The number random starting candidates for optimisation to evaluate. This will only happen for :code:`nstarts > 0` and if at least one :code:`Parameter` object is random. random_state : None, int or RandomState, optional random seed Examples -------- Define a cost function that returns a pair. The first element is the cost value and the second element is the gradient represented by a tuple. Even if the cost is a function of a single variable, the gradient must be a tuple containing one element. Augment the Scipy optimizer to take structured inputs Constant Initial values Random Initial values """
@wraps(minimizer) def new_minimizer(fun, parameters, jac=True, args=(), nstarts=0, random_state=None, **minimizer_kwargs): (array1d, fbounds), shapes = flatten( parameters, hstack=bt.hstack, shape=bt.shape, ravel=partial(bt.ravel, random_state=random_state) ) # Find best random starting candidate if we are doing random starts if nstarts > 0: array1d = _random_starts( fun=fun, parameters=parameters, jac=jac, args=args, nstarts=nstarts, random_state=random_state ) # Wrap function calls to work with wrapped minimizer flatten_args_dec = flatten_args(shapes) new_fun = flatten_args_dec(fun) # Wrap gradient calls to work with wrapped minimizer if callable(jac): new_jac = flatten_args_dec(jac) else: new_jac = jac if bool(jac): new_fun = flatten_func_grad(new_fun) result = minimizer(new_fun, array1d, jac=new_jac, args=args, bounds=fbounds, **minimizer_kwargs) result['x'] = tuple(unflatten(result['x'], shapes)) if bool(jac): result['jac'] = tuple(unflatten(result['jac'], shapes)) return result return new_minimizer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def structured_sgd(sgd): r""" Allow an SGD to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `btypes.py`, and can accept nested sequences of *any* structure of these objects to optimise! It can also optionally evaluate *random starts* (i.e. random starting candidates) if the parameter objects have been initialised with distributions. For this, an additional parameter is exposed in the :code:`minimizer` interface. Parameters fun : callable objective function that takes in arbitrary ndarrays, floats or nested sequences of these. parameters : (nested) sequences of Parameter objects Initial guess of the parameters of the objective function nstarts : int, optional The number random starting candidates for optimisation to evaluate. This will only happen for :code:`nstarts > 0` and if at least one :code:`Parameter` object is random. Examples -------- Define a cost function that returns a pair. The first element is the cost value and the second element is the gradient represented by a sequence. Even if the cost is a function of a single variable, the gradient must be a sequence containing one element. Augment the SGD optimizer to take structured inputs Data Constant Initial values Random Initial values """
@wraps(sgd) def new_sgd(fun, parameters, data, eval_obj=False, batch_size=10, args=(), random_state=None, nstarts=100, **sgd_kwargs): (array1d, fbounds), shapes = flatten(parameters, hstack=bt.hstack, shape=bt.shape, ravel=bt.ravel ) flatten_args_dec = flatten_args(shapes) new_fun = flatten_args_dec(fun) # Find best random starting candidate if we are doing random starts if eval_obj and nstarts > 0: data_gen = gen_batch(data, batch_size, random_state=random_state) array1d = _random_starts( fun=fun, parameters=parameters, jac=True, args=args, data_gen=data_gen, nstarts=nstarts, random_state=random_state ) if bool(eval_obj): new_fun = flatten_func_grad(new_fun) else: new_fun = flatten_grad(new_fun) result = sgd(new_fun, array1d, data=data, bounds=fbounds, args=args, eval_obj=eval_obj, random_state=random_state, **sgd_kwargs) result['x'] = tuple(unflatten(result['x'], shapes)) return result return new_sgd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logtrick_minimizer(minimizer): r""" Log-Trick decorator for optimizers. This decorator implements the "log trick" for optimizing positive bounded variables. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- Here is an example where we may want to enforce a particular parameter or parameters to be strictly greater than zero, Now let's enforce that the `w` are positive, Initial values array([ True, True, True], dtype=bool) Note ---- This decorator only works on unstructured optimizers. However, it can be use with structured_minimizer, so long as it is the inner wrapper. """
@wraps(minimizer) def new_minimizer(fun, x0, jac=True, bounds=None, **minimizer_kwargs): if bounds is None: return minimizer(fun, x0, jac=jac, bounds=bounds, **minimizer_kwargs) logx, expx, gradx, bounds = _logtrick_gen(bounds) # Intercept gradient if callable(jac): def new_jac(x, *fargs, **fkwargs): return gradx(jac(expx(x), *fargs, **fkwargs), x) else: new_jac = jac # Intercept objective if (not callable(jac)) and bool(jac): def new_fun(x, *fargs, **fkwargs): o, g = fun(expx(x), *fargs, **fkwargs) return o, gradx(g, x) else: def new_fun(x, *fargs, **fkwargs): return fun(expx(x), *fargs, **fkwargs) # Transform the final result result = minimizer(new_fun, logx(x0), jac=new_jac, bounds=bounds, **minimizer_kwargs) result['x'] = expx(result['x']) return result return new_minimizer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logtrick_sgd(sgd): r""" Log-Trick decorator for stochastic gradients. This decorator implements the "log trick" for optimizing positive bounded variables using SGD. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- Here is an example where we may want to enforce a particular parameter or parameters to be strictly greater than zero, Now let's enforce that the `w` are positive, Data Initial values array([ True, True], dtype=bool) Note ---- This decorator only works on unstructured optimizers. However, it can be use with structured_minimizer, so long as it is the inner wrapper. """
@wraps(sgd) def new_sgd(fun, x0, data, bounds=None, eval_obj=False, **sgd_kwargs): if bounds is None: return sgd(fun, x0, data, bounds=bounds, eval_obj=eval_obj, **sgd_kwargs) logx, expx, gradx, bounds = _logtrick_gen(bounds) if bool(eval_obj): def new_fun(x, *fargs, **fkwargs): o, g = fun(expx(x), *fargs, **fkwargs) return o, gradx(g, x) else: def new_fun(x, *fargs, **fkwargs): return gradx(fun(expx(x), *fargs, **fkwargs), x) # Transform the final result result = sgd(new_fun, logx(x0), data, bounds=bounds, eval_obj=eval_obj, **sgd_kwargs) result['x'] = expx(result['x']) return result return new_sgd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_grad(func): r""" Decorator to flatten structured gradients. Examples -------- 2 (3,) () array([ 0.125, 0.025, -0.05 ]) True array([ 0.125, 0.025, -0.05 , 0.15 ]) """
@wraps(func) def new_func(*args, **kwargs): return flatten(func(*args, **kwargs), returns_shapes=False) return new_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_func_grad(func): r""" Decorator to flatten structured gradients and return objective. Examples -------- True 2 (3,) () array([ 0.125, 0.025, -0.05 ]) True True array([ 0.125, 0.025, -0.05 , 0.15 ]) """
@wraps(func) def new_func(*args, **kwargs): val, grad = func(*args, **kwargs) return val, flatten(grad, returns_shapes=False) return new_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_args(shapes): r""" Decorator to flatten structured arguments to a function. Examples -------- True True Some other curious applications array([ 1.86 , 5.301, -3.72 ]) array([ 1.86 , 5.301, -3.72 ]) (15, 9) array([-5. , -4.5, -4. , -3.5, -3. , -2.5, -2. , -1.5, -1. ]) (15, 9) array([-0.5, 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5]) """
def flatten_args_dec(func): @wraps(func) def new_func(array1d, *args, **kwargs): args = tuple(unflatten(array1d, shapes)) + args return func(*args, **kwargs) return new_func return flatten_args_dec
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _random_starts(fun, parameters, jac, args, nstarts, random_state, data_gen=None): """Generate and evaluate random starts for Parameter objects."""
if nstarts < 1: raise ValueError("nstarts has to be greater than or equal to 1") # Check to see if there are any random parameter types anyrand = any(flatten(map_recursive(lambda p: p.is_random, parameters), returns_shapes=False)) if not anyrand: log.info("No random parameters, not doing any random starts") params = map_recursive(lambda p: p.value, parameters, output_type=list) return params log.info("Evaluating random starts...") # Deal with gradient returns from objective function if jac is True: call_fun = lambda *fargs: fun(*fargs)[0] else: # No gradient returns or jac is callable call_fun = fun # Randomly draw parameters and evaluate function def fun_eval(): batch = next(data_gen) if data_gen else () params = map_recursive(lambda p: p.rvs(random_state), parameters, output_type=list) obj = call_fun(*chain(params, batch, args)) return obj, params # Test randomly drawn parameters sample_gen = (fun_eval() for _ in range(nstarts)) obj, params = min(sample_gen, key=lambda t: t[0]) log.info("Best start found with objective = {}".format(obj)) return flatten(params, returns_shapes=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _logtrick_gen(bounds): """Generate warping functions and new bounds for the log trick."""
# Test which parameters we can apply the log trick too ispos = np.array([isinstance(b, bt.Positive) for b in bounds], dtype=bool) nispos = ~ispos # Functions that implement the log trick def logx(x): xwarp = np.empty_like(x) xwarp[ispos] = np.log(x[ispos]) xwarp[nispos] = x[nispos] return xwarp def expx(xwarp): x = np.empty_like(xwarp) x[ispos] = np.exp(xwarp[ispos]) x[nispos] = xwarp[nispos] return x def gradx(grad, xwarp): gwarp = np.empty_like(grad) gwarp[ispos] = grad[ispos] * np.exp(xwarp[ispos]) gwarp[nispos] = grad[nispos] return gwarp # Redefine bounds as appropriate for new ranges for numerical stability for i, (b, pos) in enumerate(zip(bounds, ispos)): if pos: upper = EXPMAX if b.upper is None else np.log(b.upper) bounds[i] = bt.Bound(lower=LOGMINPOS, upper=upper) return logx, expx, gradx, bounds
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_url(cls, url): """ Functon will check given url and try to verify if it's a valid link. Sometimes it may happened that mercurial will issue basic auth request that can cause whole API to hang when used from python or other external calls. On failures it'll raise urllib2.HTTPError """
# check first if it's not an local url if os.path.isdir(url) or url.startswith('file:'): return True if('+' in url[:url.find('://')]): url = url[url.find('+') + 1:] handlers = [] test_uri, authinfo = hg_url(url).authinfo() if not test_uri.endswith('info/refs'): test_uri = test_uri.rstrip('/') + '/info/refs' if authinfo: #create a password manager passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm() passmgr.add_password(*authinfo) handlers.extend((httpbasicauthhandler(passmgr), httpdigestauthhandler(passmgr))) o = urllib2.build_opener(*handlers) o.addheaders = [('User-Agent', 'git/1.7.8.0')] # fake some git q = {"service": 'git-upload-pack'} qs = '?%s' % urllib.urlencode(q) cu = "%s%s" % (test_uri, qs) req = urllib2.Request(cu, None, {}) try: resp = o.open(req) return resp.code == 200 except Exception, e: # means it cannot be cloned raise urllib2.URLError("[%s] %s" % (url, e))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_revision(self, revision): """ For git backend we always return integer here. This way we ensure that changset's revision attribute would become integer. """
is_null = lambda o: len(o) == revision.count('0') try: self.revisions[0] except (KeyError, IndexError): raise EmptyRepositoryError("There are no changesets yet") if revision in (None, '', 'tip', 'HEAD', 'head', -1): return self.revisions[-1] is_bstr = isinstance(revision, (str, unicode)) if ((is_bstr and revision.isdigit() and len(revision) < 12) or isinstance(revision, int) or is_null(revision)): try: revision = self.revisions[int(revision)] except Exception: raise ChangesetDoesNotExistError("Revision %s does not exist " "for this repository" % (revision)) elif is_bstr: # get by branch/tag name _ref_revision = self._parsed_refs.get(revision) if _ref_revision: # and _ref_revision[1] in ['H', 'RH', 'T']: return _ref_revision[0] _tags_shas = self.tags.values() # maybe it's a tag ? we don't have them in self.revisions if revision in _tags_shas: return _tags_shas[_tags_shas.index(revision)] elif not SHA_PATTERN.match(revision) or revision not in self.revisions: raise ChangesetDoesNotExistError("Revision %s does not exist " "for this repository" % (revision)) # Ensure we return full id if not SHA_PATTERN.match(str(revision)): raise ChangesetDoesNotExistError("Given revision %s not recognized" % revision) return revision
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_hook_location(self): """ returns absolute path to location where hooks are stored """
loc = os.path.join(self.path, 'hooks') if not self.bare: loc = os.path.join(self.path, '.git', 'hooks') return loc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone(self, url, update_after_clone=True, bare=False): """ Tries to clone changes from external location. :param update_after_clone: If set to ``False``, git won't checkout working directory :param bare: If set to ``True``, repository would be cloned into *bare* git repository (no working directory at all). """
url = self._get_url(url) cmd = ['clone'] if bare: cmd.append('--bare') elif not update_after_clone: cmd.append('--no-checkout') cmd += ['--', '"%s"' % url, '"%s"' % self.path] cmd = ' '.join(cmd) # If error occurs run_git_command raises RepositoryError already self.run_git_command(cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate_from_changeset(self, changeset): """ Returns full html line for single changeset per annotated line. """
if self.annotate_from_changeset_func: return self.annotate_from_changeset_func(changeset) else: return ''.join((changeset.id, '\n'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _obtain_lock_or_raise(self): """Create a lock file as flag for other instances, mark our instance as lock-holder :raise IOError: if a lock was already present or a lock file could not be written"""
if self._has_lock(): return lock_file = self._lock_file_path() if os.path.isfile(lock_file): raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file)) try: fd = os.open(lock_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0) os.close(fd) except OSError,e: raise IOError(str(e)) self._owns_lock = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def objectify_uri(relative_uri): '''Converts uris from path syntax to a json-like object syntax. In addition, url escaped characters are unescaped, but non-ascii characters a romanized using the unidecode library. Examples: "/blog/3/comments" becomes "blog[3].comments" "car/engine/piston" becomes "car.engine.piston" ''' def path_clean(chunk): if not chunk: return chunk if re.match(r'\d+$', chunk): return '[{0}]'.format(chunk) else: return '.' + chunk if six.PY2: byte_arr = relative_uri.encode('utf-8') else: byte_arr = relative_uri unquoted = decode(unquote(byte_arr), 'utf-8') nice_uri = unidecode.unidecode(unquoted) return ''.join(path_clean(c) for c in nice_uri.split('/'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse_media_type(media_type): '''Returns type, subtype, parameter tuple from an http media_type. Can be applied to the 'Accept' or 'Content-Type' http header fields. ''' media_type, sep, parameter = str(media_type).partition(';') media_type, sep, subtype = media_type.partition('/') return tuple(x.strip() or None for x in (media_type, subtype, parameter))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getpath(d, json_path, default=None, sep='.'): '''Gets a value nested in dictionaries containing dictionaries. Returns the default if any key in the path doesn't exist. ''' for key in json_path.split(sep): try: d = d[key] except (KeyError, TypeError): return default return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getstate(d): '''Deep copies a dict, and returns it without the keys _links and _embedded ''' if not isinstance(d, dict): raise TypeError("Can only get the state of a dictionary") cpd = copy.deepcopy(d) cpd.pop('_links', None) cpd.pop('_embedded', None) return cpd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def append_with(self, obj, **properties): '''Add an item to the dictionary with the given metadata properties''' for prop, val in properties.items(): val = self.serialize(val) self._meta.setdefault(prop, {}).setdefault(val, []).append(obj) self.append(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_by(self, prop, val, raise_exc=False): '''Retrieve an item from the dictionary with the given metadata properties. If there is no such item, None will be returned, if there are multiple such items, the first will be returned.''' try: val = self.serialize(val) return self._meta[prop][val][0] except (KeyError, IndexError): if raise_exc: raise else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getall_by(self, prop, val): '''Retrieves all items from the dictionary with the given metadata''' try: val = self.serialize(val) return self._meta[prop][val][:] # return a copy of the list except KeyError: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_replace_state_separator(data, old, new): """Replace state separator. Parameters data : `dict` of `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Data. old : `str` Old separator. new : `str` New separator. """
for key, dataset in data.items(): data[key] = dict( (k.replace(old, new), v) for k, v in dataset.items() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_get_dataset(data, key, create=False): """Get a dataset. Parameters data : `None` or `dict` of `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Data. key : `str` Dataset key. create : `bool`, optional Create a dataset if it does not exist. Returns ------- `None` or `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) """
if data is None: return None try: return data[key] except KeyError: if create: dataset = {} data[key] = dataset return dataset else: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_link(dataset, source, target, count=1): """Add a link. Parameters dataset : `dict` of ([`int`, `str`] or [`list` of `int`, `list` of `str`]) Dataset. source : `iterable` of `str` Link source. target : `str` Link target. count : `int`, optional Link count (default: 1). """
try: node = dataset[source] values, links = node if isinstance(links, list): try: idx = links.index(target) values[idx] += count except ValueError: links.append(target) values.append(count) elif links == target: node[0] += count else: node[0] = [values, count] node[1] = [links, target] except KeyError: dataset[source] = [count, target]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chain_user_names(users, exclude_user, truncate=35): """Tag to return a truncated chain of user names."""
if not users or not isinstance(exclude_user, get_user_model()): return '' return truncatechars( ', '.join(u'{}'.format(u) for u in users.exclude(pk=exclude_user.pk)), truncate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url(self, key): """Creates a full URL to the API using urls dict """
return urlunparse((self.protocol, '%s:%s' % (self.domain, self.port), '%s/api/v1%s' % (self.prefix, URLS[key]), '', '', ''))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_manifest_valid(self, manifest_id): """Check validation shortcut :param: manifest_id (string) id received in :method:`validate_manifest` :returns: * True if manifest was valid * None if manifest wasn't checked yet * validation dict if not valid """
response = self.get_manifest_validation_result(manifest_id) if response.status_code != 200: raise Exception(response.status_code) content = json.loads(response.content) if not content['processed']: return None if content['valid']: return True return content['validation']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, app_id, data): """Update app identified by app_id with data :params: * app_id (int) id in the marketplace received with :method:`create` * data (dict) some keys are required: * *name*: the title of the app. Maximum length 127 characters. * *summary*: the summary of the app. Maximum length 255 characters. * *categories*: a list of the categories, at least two of the category ids provided from the category api (see below). * *support_email*: the email address for support. * *device_types*: a list of the device types at least one of: 'desktop', 'phone', 'tablet'. * *payment_type*: only choice at this time is 'free'. :returns: HttResponse: * status_code (int) 202 if successful * content (dict) or empty if successful """
assert ('name' in data and data['name'] and 'summary' in data and 'categories' in data and data['categories'] and 'support_email' in data and data['support_email'] and 'device_types' in data and data['device_types'] and 'payment_type' in data and data['payment_type'] and 'privacy_policy' in data and data['privacy_policy']) return self.conn.fetch('PUT', self.url('app') % app_id, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_screenshot(self, app_id, filename, position=1): """Add a screenshot to the web app identified by by ``app_id``. Screenshots are ordered by ``position``. :returns: HttpResponse: * status_code (int) 201 is successful * content (dict) containing screenshot data """
# prepare file for upload with open(filename, 'rb') as s_file: s_content = s_file.read() s_encoded = b64encode(s_content) url = self.url('create_screenshot') % app_id mtype, encoding = mimetypes.guess_type(filename) if mtype is None: mtype = 'image/jpeg' data = {'position': position, 'file': {'type': mtype, 'data': s_encoded}} return self.conn.fetch('POST', url, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_content_ratings(self, app_id, submission_id, security_code): """Add content ratings to the web app identified by by ``app_id``, using the specified submission id and security code. :returns: HttpResponse: * status_code (int) 201 is successful """
url = self.url('content_ratings') % app_id return self.conn.fetch('POST', url, {'submission_id': '%s' % submission_id, 'security_code': '%s' % security_code })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self): """Convert the scanner to JSON. Returns ------- `dict` JSON data. """
data = super().save() data['expr'] = self.expr.pattern data['default_end'] = self.default_end return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_branches(self, closed=False): """ Get's branches for this repository Returns only not closed branches by default :param closed: return also closed branches for mercurial """
if self._empty: return {} def _branchtags(localrepo): """ Patched version of mercurial branchtags to not return the closed branches :param localrepo: locarepository instance """ bt = {} bt_closed = {} for bn, heads in localrepo.branchmap().iteritems(): tip = heads[-1] if 'close' in localrepo.changelog.read(tip)[5]: bt_closed[bn] = tip else: bt[bn] = tip if closed: bt.update(bt_closed) return bt sortkey = lambda ctx: ctx[0] # sort by name _branches = [(safe_unicode(n), hex(h),) for n, h in _branchtags(self._repo).items()] return OrderedDict(sorted(_branches, key=sortkey, reverse=False))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_repo(self, create, src_url=None, update_after_clone=False): """ Function will check for mercurial repository in given path and return a localrepo object. If there is no repository in that path it will raise an exception unless ``create`` parameter is set to True - in that case repository would be created and returned. If ``src_url`` is given, would try to clone repository from the location at given clone_point. Additionally it'll make update to working copy accordingly to ``update_after_clone`` flag """
try: if src_url: url = str(self._get_url(src_url)) opts = {} if not update_after_clone: opts.update({'noupdate': True}) try: MercurialRepository._check_url(url) clone(self.baseui, url, self.path, **opts) # except urllib2.URLError: # raise Abort("Got HTTP 404 error") except Exception: raise # Don't try to create if we've already cloned repo create = False return localrepository(self.baseui, self.path, create=create) except (Abort, RepoError), err: if create: msg = "Cannot create repository at %s. Original error was %s"\ % (self.path, err) else: msg = "Not valid repository at %s. Original error was %s"\ % (self.path, err) raise RepositoryError(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_revision(self, revision): """ Get's an ID revision given as str. This will always return a fill 40 char revision number :param revision: str or int or None """
if self._empty: raise EmptyRepositoryError("There are no changesets yet") if revision in [-1, 'tip', None]: revision = 'tip' try: revision = hex(self._repo.lookup(revision)) except (IndexError, ValueError, RepoLookupError, TypeError): raise ChangesetDoesNotExistError("Revision %s does not " "exist for this repository" % (revision)) return revision
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_changeset(self, revision=None): """ Returns ``MercurialChangeset`` object representing repository's changeset at the given ``revision``. """
revision = self._get_revision(revision) changeset = MercurialChangeset(repository=self, revision=revision) return changeset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format(self, parts): """Format generated text. Parameters parts : `iterable` of `str` Text parts. """
text = self.storage.state_separator.join(parts) return self.formatter(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_replies(self, max_length, state_size, reply_to, dataset): """Generate replies. Parameters max_length : `int` or `None` Maximum sentence length. state_size : `int` State size. reply_to : `str` Input string. dataset: `str` Dataset key prefix. Returns ------- `generator` of `str` Generated texts. """
state_sets = self.get_reply_states( reply_to, dataset + state_size_dataset(state_size) ) if not state_sets: yield from self.generate_cont(max_length, state_size, None, False, dataset) return random.shuffle(state_sets) generate = lambda state, backward: self.generate( state_size, state, dataset, backward ) for states in cycle(state_sets): state = random.choice(states) parts = chain( reversed(list(generate(state, True))), (state,), generate(state, False) ) parts = islice(parts, 0, max_length) yield self.format(parts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(self): """ Returns combined size in bytes for all repository files """
size = 0 try: tip = self.get_changeset() for topnode, dirs, files in tip.walk('/'): for f in files: size += tip.get_file_size(f.path) for dir in dirs: for f in files: size += tip.get_file_size(f.path) except RepositoryError: pass return size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_changesets(self, start=None, end=None, start_date=None, end_date=None, branch_name=None, reverse=False): """ Returns iterator of ``MercurialChangeset`` objects from start to end not inclusive This should behave just like a list, ie. end is not inclusive :param start: None or str :param end: None or str :param start_date: :param end_date: :param branch_name: :param reversed: """
raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_chunked_archive(self, **kwargs): """ Returns iterable archive. Tiny wrapper around ``fill_archive`` method. :param chunk_size: extra parameter which controls size of returned chunks. Default:8k. """
chunk_size = kwargs.pop('chunk_size', 8192) stream = kwargs.get('stream') self.fill_archive(**kwargs) while True: data = stream.read(chunk_size) if not data: break yield data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_dict(self): """ Returns dictionary with changeset's attributes and their values. """
data = get_dict_for_attrs(self, ['id', 'raw_id', 'short_id', 'revision', 'date', 'message']) data['author'] = {'name': self.author_name, 'email': self.author_email} data['added'] = [node.path for node in self.added] data['changed'] = [node.path for node in self.changed] data['removed'] = [node.path for node in self.removed] return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ipaths(self): """ Returns generator of paths from nodes marked as added, changed or removed. """
for node in itertools.chain(self.added, self.changed, self.removed): yield node.path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_integrity(self, parents=None): """ Checks in-memory changeset's integrity. Also, sets parents if not already set. :raises CommitError: if any error occurs (i.e. ``NodeDoesNotExistError``). """
if not self.parents: parents = parents or [] if len(parents) == 0: try: parents = [self.repository.get_changeset(), None] except EmptyRepositoryError: parents = [None, None] elif len(parents) == 1: parents += [None] self.parents = parents # Local parents, only if not None parents = [p for p in self.parents if p] # Check nodes marked as added for p in parents: for node in self.added: try: p.get_node(node.path) except NodeDoesNotExistError: pass else: raise NodeAlreadyExistsError("Node at %s already exists " "at %s" % (node.path, p)) # Check nodes marked as changed missing = set(self.changed) not_changed = set(self.changed) if self.changed and not parents: raise NodeDoesNotExistError(str(self.changed[0].path)) for p in parents: for node in self.changed: try: old = p.get_node(node.path) missing.remove(node) if old.content != node.content: not_changed.remove(node) except NodeDoesNotExistError: pass if self.changed and missing: raise NodeDoesNotExistError("Node at %s is missing " "(parents: %s)" % (node.path, parents)) if self.changed and not_changed: raise NodeNotChangedError("Node at %s wasn't actually changed " "since parents' changesets: %s" % (not_changed.pop().path, parents) ) # Check nodes marked as removed if self.removed and not parents: raise NodeDoesNotExistError("Cannot remove node at %s as there " "were no parents specified" % self.removed[0].path) really_removed = set() for p in parents: for node in self.removed: try: p.get_node(node.path) really_removed.add(node) except ChangesetError: pass not_removed = set(self.removed) - really_removed if not_removed: raise NodeDoesNotExistError("Cannot remove node at %s from " "following parents: %s" % (not_removed[0], parents))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_file_content(self, path): """ Returns content of the file at given ``path``. """
id = self._get_id_for_path(path) blob = self.repository._repo[id] return blob.as_pretty_string()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_file_size(self, path): """ Returns size of the file at given ``path``. """
id = self._get_id_for_path(path) blob = self.repository._repo[id] return blob.raw_length()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def affected_files(self): """ Get's a fast accessible file changes for given changeset """
added, modified, deleted = self._changes_cache return list(added.union(modified).union(deleted))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_paths_for_status(self, status): """ Returns sorted list of paths for given ``status``. :param status: one of: *added*, *modified* or *deleted* """
added, modified, deleted = self._changes_cache return sorted({ 'added': list(added), 'modified': list(modified), 'deleted': list(deleted)}[status] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def added(self): """ Returns list of added ``FileNode`` objects. """
if not self.parents: return list(self._get_file_nodes()) return AddedFileNodesGenerator([n for n in self._get_paths_for_status('added')], self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def changed(self): """ Returns list of modified ``FileNode`` objects. """
if not self.parents: return [] return ChangedFileNodesGenerator([n for n in self._get_paths_for_status('modified')], self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removed(self): """ Returns list of removed ``FileNode`` objects. """
if not self.parents: return [] return RemovedFileNodesGenerator([n for n in self._get_paths_for_status('deleted')], self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sgd(fun, x0, data, args=(), bounds=None, batch_size=10, maxiter=5000, updater=None, eval_obj=False, random_state=None): """ Stochastic Gradient Descent. Parameters fun : callable the function to *minimize*, this must have the signature ``[obj,]`` ``sgd`` if an objective function value is going to be returned by ``fun``. x0 : ndarray a sequence/1D array of initial values for the parameters to learn. data : ndarray a numpy array or sequence of data to input into ``fun``. This will be split along the first axis (axis=0), and then input into ``fun``. args : sequence, optional an optional sequence of arguments to give to fun. bounds : sequence, optional Bounds for variables, (min, max) pairs for each element in x, defining the bounds on that parameter. Use None for one of min or max when there is no bound in that direction. batch_size : int, optional The number of observations in an SGD batch. maxiter : int, optional Number of mini-batch iterations before optimization terminates. updater : SGDUpdater, optional The type of gradient update to use, by default this is Adam. eval_obj : bool, optional This indicates whether or not ``fun`` also evaluates and returns the objective function value. If this is true, ``fun`` must return ``(obj, grad)`` and then a list of objective function values is also returned. random_state : int or RandomState, optional random seed Returns ------- res : OptimizeResult x : narray the final result norms : list the list of gradient norms message : str the convergence condition ('maxiter reached' or error) objs : list the list of objective function evaluations if ``eval_obj`` is True. fun : float the final objective function evaluation if ``eval_obj`` is True. """
if updater is None: updater = Adam() # Make sure we aren't using a recycled updater updater.reset() N = _len_data(data) x = np.array(x0, copy=True, dtype=float) D = x.shape[0] # Make sure we have a valid batch size batch_size = min(batch_size, N) # Process bounds if bounds is not None: if len(bounds) != D: raise ValueError("The dimension of the bounds does not match x0!") lower, upper = zip(*map(normalize_bound, bounds)) lower = np.array(lower) upper = np.array(upper) # Learning Records obj = None objs = [] norms = [] for batch in gen_batch(data, batch_size, maxiter, random_state): if not eval_obj: grad = fun(x, *chain(batch, args)) else: obj, grad = fun(x, *chain(batch, args)) objs.append(obj) norms.append(np.linalg.norm(grad)) # Truncate gradients if bounded if bounds is not None: xlower = x <= lower grad[xlower] = np.minimum(grad[xlower], 0) xupper = x >= upper grad[xupper] = np.maximum(grad[xupper], 0) # perform update x = updater(x, grad) # Trucate steps if bounded if bounds is not None: x = np.clip(x, lower, upper) # Format results res = OptimizeResult( x=x, norms=norms, message='maxiter reached', fun=obj, objs=objs ) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gen_batch(data, batch_size, maxiter=np.inf, random_state=None): """ Create random batches for Stochastic gradients. Batch index generator for SGD that will yeild random batches for a a defined number of iterations, which can be infinite. This generator makes consecutive passes through the data, drawing without replacement on each pass. Parameters data : ndarray or sequence of ndarrays The data, can be a matrix X, (X,y) tuples etc batch_size : int number of data points in each batch. maxiter : int, optional The number of iterations random_state : int or RandomState, optional random seed Yields ------ ndarray or sequence : with each array length ``batch_size``, i.e. a subset of data. """
perms = endless_permutations(_len_data(data), random_state) it = 0 while it < maxiter: it += 1 ind = np.array([next(perms) for _ in range(batch_size)]) yield _split_data(data, ind)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_bound(bound): """ Replace ``None`` with + or - inf in bound tuples. Examples -------- (2.6, 7.2) (-inf, 7.2) (2.6, inf) (-inf, inf) This operation is idempotent: (-inf, inf) """
min_, max_ = bound if min_ is None: min_ = -float('inf') if max_ is None: max_ = float('inf') return min_, max_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset the state of this updater for a new optimisation problem."""
self.__init__(self.alpha, self.beta1, self.beta2, self.epsilon)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aslist(obj, sep=None, strip=True): """ Returns given string separated by sep as list :param obj: :param sep: :param strip: """
if isinstance(obj, (basestring)): lst = obj.split(sep) if strip: lst = [v.strip() for v in lst] return lst elif isinstance(obj, (list, tuple)): return obj elif obj is None: return [] else: return [obj]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_unicode(str_, from_encoding=None): """ safe unicode function. Does few trick to turn str_ into unicode In case of UnicodeDecode error we try to return it with encoding detected by chardet library if it fails fallback to unicode with errors replaced :param str_: string to decode :rtype: unicode :returns: unicode object """
if isinstance(str_, unicode): return str_ if not from_encoding: from vcs.conf import settings from_encoding = settings.DEFAULT_ENCODINGS if not isinstance(from_encoding, (list, tuple)): from_encoding = [from_encoding] try: return unicode(str_) except UnicodeDecodeError: pass for enc in from_encoding: try: return unicode(str_, enc) except UnicodeDecodeError: pass try: import chardet encoding = chardet.detect(str_)['encoding'] if encoding is None: raise Exception() return str_.decode(encoding) except (ImportError, UnicodeDecodeError, Exception): return unicode(str_, from_encoding[0], 'replace')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def safe_str(unicode_, to_encoding=None): """ safe str function. Does few trick to turn unicode_ into string In case of UnicodeEncodeError we try to return it with encoding detected by chardet library if it fails fallback to string with errors replaced :param unicode_: unicode to encode :rtype: str :returns: str object """
# if it's not basestr cast to str if not isinstance(unicode_, basestring): return str(unicode_) if isinstance(unicode_, str): return unicode_ if not to_encoding: from vcs.conf import settings to_encoding = settings.DEFAULT_ENCODINGS if not isinstance(to_encoding, (list, tuple)): to_encoding = [to_encoding] for enc in to_encoding: try: return unicode_.encode(enc) except UnicodeEncodeError: pass try: import chardet encoding = chardet.detect(unicode_)['encoding'] if encoding is None: raise UnicodeEncodeError() return unicode_.encode(encoding) except (ImportError, UnicodeEncodeError): return unicode_.encode(to_encoding[0], 'replace') return safe_str
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def author_name(author): """ get name of author, or else username. It'll try to find an email in the author string and just cut it off to get the username """
if not '@' in author: return author else: return author.replace(author_email(author), '').replace('<', '')\ .replace('>', '').strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fit(self, X, y): """ Learn the hyperparameters of a Bayesian linear regressor. Parameters X : ndarray (N, d) array input dataset (N samples, d dimensions). y : ndarray (N,) array targets (N samples) Returns ------- self Notes ----- This actually optimises the evidence lower bound on log marginal likelihood, rather than log marginal likelihood directly. In the case of a full posterior convariance matrix, this bound is tight and the exact solution will be found (modulo local minima for the hyperparameters). This uses the python logging module for displaying learning status. To view these messages have something like, .. code :: import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) in your calling code. """
X, y = check_X_y(X, y) self.obj_ = -np.inf # Make list of parameters and decorate optimiser to undestand this params = [self.var, self.basis.regularizer, self.basis.params] nmin = structured_minimizer(logtrick_minimizer(minimize)) # Close over objective and learn parameters elbo = partial(StandardLinearModel._elbo, self, X, y) res = nmin(elbo, params, method='L-BFGS-B', jac=True, tol=self.tol, options={'maxiter': self.maxiter, 'maxcor': 100}, random_state=self.random_, nstarts=self.nstarts ) # Upack learned parameters and report self.var_, self.regularizer_, self.hypers_ = res.x log.info("Done! ELBO = {}, var = {}, reg = {}, hypers = {}, " "message = {}." .format(-res['fun'], self.var_, self.regularizer_, self.hypers_, res.message) ) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict_moments(self, X): """ Full predictive distribution from Bayesian linear regression. Parameters X : ndarray (N*,d) array query input dataset (N* samples, d dimensions). Returns ------- Ey : ndarray The expected value of y* for the query inputs, X* of shape (N*,). Vy : ndarray The expected variance of y* for the query inputs, X* of shape (N*,). """
check_is_fitted(self, ['var_', 'regularizer_', 'weights_', 'covariance_', 'hypers_']) X = check_array(X) Phi = self.basis.transform(X, *atleast_list(self.hypers_)) Ey = Phi.dot(self.weights_) Vf = (Phi.dot(self.covariance_) * Phi).sum(axis=1) return Ey, Vf + self.var_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def emit_iana_rels(rels_url): '''Fetches the IANA link relation registry''' text = requests.get(rels_url).text.encode('ascii', 'ignore') xml = objectify.fromstring(text) iana_rels = {str(rec.value): str(rec.description) for rec in xml.registry.record} keys = sorted(iana_rels) print('# IANA link relation registry last updated on:', xml.updated) print('# Obtained from', rels_url) print() print('iana_rels = {') for key in keys: print(' {0!r}: ('.format(key)) desc_list = list(linewrap(iana_rels[key], width=68)) for i, line in enumerate(desc_list): line_ = line.replace('"', '\\"') # escape double quotes if i < len(desc_list) - 1: print(' "{0} "'.format(line_)) else: print(' "{0}"'.format(line_)) print(' ),') print('}')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dirs_for_path(*paths): """ Returns list of directories, including intermediate. """
for path in paths: head = path while head: head, tail = os.path.split(head) if head: yield head else: # We don't need to yield empty path break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tables(self): """Get all table names. Returns ------- `set` of `str` """
self.cursor.execute( 'SELECT name FROM sqlite_master WHERE type="table"' ) return set(x[0] for x in self.cursor.fetchall())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_node(self, value): """Get node ID by value. If a node with the specified value does not exist, create it and return its ID. Parameters value : `str` Node value. Returns ------- `int` Node ID. """
while True: self.cursor.execute( 'SELECT id FROM nodes WHERE value=?', (value,) ) node = self.cursor.fetchone() if node is not None: return node[0] self.cursor.execute( 'INSERT INTO nodes (value) VALUES (?)', (value,) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_main_table(self): """Write generator settings to database. """
data = (json.dumps(self.settings),) self.cursor.execute(''' CREATE TABLE IF NOT EXISTS main ( settings TEXT NOT NULL DEFAULT "{}" ) ''') self.cursor.execute('SELECT * FROM main') if self.cursor.fetchall() == []: self.cursor.execute('INSERT INTO main (settings) VALUES (?)', data) else: self.cursor.execute('UPDATE main SET settings=?', data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_node_tables(self): """Create node and link tables if they don't exist. """
self.cursor.execute('PRAGMA foreign_keys=1') self.cursor.execute(''' CREATE TABLE IF NOT EXISTS datasets ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, key TEXT NOT NULL ) ''') self.cursor.execute(''' CREATE TABLE IF NOT EXISTS nodes ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, value TEXT NOT NULL ) ''') self.cursor.execute(''' CREATE TABLE IF NOT EXISTS links ( dataset REFERENCES datasets (id), source REFERENCES nodes (id), target REFERENCES nodes (id), value TEXT, bvalue TEXT, count INTEGER NOT NULL DEFAULT 1 ) ''') self.cursor.execute( 'CREATE UNIQUE INDEX IF NOT EXISTS node ON nodes (value)' ) self.cursor.execute( 'CREATE INDEX IF NOT EXISTS link_source ON links (source, dataset)' ) self.cursor.execute( 'CREATE INDEX IF NOT EXISTS link_target ON links (target, dataset)' )