_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q233200
to_ds9_meta
train
def to_ds9_meta(shape_meta): """ Makes the meta data DS9 compatible by filtering and mapping the valid keys Parameters ---------- shape_meta: dict meta attribute of a `regions.Shape` object Returns ------- meta : dict DS9 compatible meta dictionary """ # meta k...
python
{ "resource": "" }
q233201
_to_io_meta
train
def _to_io_meta(shape_meta, valid_keys, key_mappings): """ This is used to make meta data compatible with a specific io by filtering and mapping to it's valid keys Parameters ---------- shape_meta: dict meta attribute of a `regions.Region` object valid_keys : python list Con...
python
{ "resource": "" }
q233202
Shape.convert_coords
train
def convert_coords(self): """ Process list of coordinates This mainly searches for tuple of coordinates in the coordinate list and creates a SkyCoord or PixCoord object from them if appropriate for a given region type. This involves again some coordinate transformation, ...
python
{ "resource": "" }
q233203
Shape._convert_sky_coords
train
def _convert_sky_coords(self): """ Convert to sky coordinates """ parsed_angles = [(x, y) for x, y in zip(self.coord[:-1:2], self.coord[1::2]) if (isinstance(x, coordinates.Angle) and isinstance(y, coordinates.Angle)) ...
python
{ "resource": "" }
q233204
Shape._convert_pix_coords
train
def _convert_pix_coords(self): """ Convert to pixel coordinates, `regions.PixCoord` """ if self.region_type in ['polygon', 'line']: # have to special-case polygon in the phys coord case # b/c can't typecheck when iterating as in sky coord case coords =...
python
{ "resource": "" }
q233205
Shape.to_region
train
def to_region(self): """ Converts to region, ``regions.Region`` object """ coords = self.convert_coords() log.debug(coords) viz_keywords = ['color', 'dash', 'dashlist', 'width', 'font', 'symsize', 'symbol', 'symsize', 'fontsize', 'fontstyle', 'use...
python
{ "resource": "" }
q233206
Shape.check_crtf
train
def check_crtf(self): """ Checks for CRTF compatibility. """ if self.region_type not in regions_attributes: raise ValueError("'{0}' is not a valid region type in this package" "supported by CRTF".format(self.region_type)) if self.coordsys...
python
{ "resource": "" }
q233207
Shape.check_ds9
train
def check_ds9(self): """ Checks for DS9 compatibility. """ if self.region_type not in regions_attributes: raise ValueError("'{0}' is not a valid region type in this package" "supported by DS9".format(self.region_type)) if self.coordsys no...
python
{ "resource": "" }
q233208
Shape._validate
train
def _validate(self): """ Checks whether all the attributes of this object is valid. """ if self.region_type not in regions_attributes: raise ValueError("'{0}' is not a valid region type in this package" .format(self.region_type)) if self....
python
{ "resource": "" }
q233209
read_crtf
train
def read_crtf(filename, errors='strict'): """ Reads a CRTF region file and returns a list of region objects. Parameters ---------- filename : `str` The file path errors : ``warn``, ``ignore``, ``strict``, optional The error handling scheme to use for handling parsing errors. ...
python
{ "resource": "" }
q233210
CRTFParser.parse_line
train
def parse_line(self, line): """ Parses a single line. """ # Skip blanks if line == '': return # Skip comments if regex_comment.search(line): return # Special case / header: parse global parameters into metadata global_par...
python
{ "resource": "" }
q233211
CRTFRegionParser.parse
train
def parse(self): """ Starting point to parse the CRTF region string. """ self.convert_meta() self.coordsys = self.meta.get('coord', 'image').lower() self.set_coordsys() self.convert_coordinates() self.make_shape()
python
{ "resource": "" }
q233212
CRTFRegionParser.set_coordsys
train
def set_coordsys(self): """ Mapping to astropy's coordinate system name # TODO: needs expert attention (Most reference systems are not mapped) """ if self.coordsys.lower() in self.coordsys_mapping: self.coordsys = self.coordsys_mapping[self.coordsys.lower()]
python
{ "resource": "" }
q233213
CRTFRegionParser.convert_coordinates
train
def convert_coordinates(self): """ Convert coordinate string to `~astropy.coordinates.Angle` or `~astropy.units.quantity.Quantity` objects """ coord_list_str = regex_coordinate.findall(self.reg_str) + regex_length.findall(self.reg_str) coord_list = [] if self.region_type...
python
{ "resource": "" }
q233214
CRTFRegionParser.convert_meta
train
def convert_meta(self): """ Parses the meta_str to python dictionary and stores in ``meta`` attribute. """ if self.meta_str: self.meta_str = regex_meta.findall(self.meta_str + ',') if self.meta_str: for par in self.meta_str: if par[0] is no...
python
{ "resource": "" }
q233215
fits_region_objects_to_table
train
def fits_region_objects_to_table(regions): """ Converts list of regions to FITS region table. Parameters ---------- regions : list List of `regions.Region` objects Returns ------- region_string : `~astropy.table.Table` FITS region table Examples -------- >...
python
{ "resource": "" }
q233216
write_fits_region
train
def write_fits_region(filename, regions, header=None): """ Converts list of regions to FITS region table and write to a file. Parameters ---------- filename: str Filename in which the table is to be written. Default is 'new.fits' regions: list List of `regions.Region` objects ...
python
{ "resource": "" }
q233217
make_example_dataset
train
def make_example_dataset(data='simulated', config=None): """Make example dataset. This is a factory function for ``ExampleDataset`` objects. The following config options are available (default values shown): * ``crval = 0, 0`` * ``crpix = 180, 90`` * ``cdelt = -1, 1`` * ``shape = 180, 360...
python
{ "resource": "" }
q233218
_table_to_bintable
train
def _table_to_bintable(table): """Convert `~astropy.table.Table` to `astropy.io.fits.BinTable`.""" data = table.as_array() header = fits.Header() header.update(table.meta) name = table.meta.pop('name', None) return fits.BinTableHDU(data, header, name=name)
python
{ "resource": "" }
q233219
read_ds9
train
def read_ds9(filename, errors='strict'): """ Read a DS9 region file in as a `list` of `~regions.Region` objects. Parameters ---------- filename : `str` The file path errors : ``warn``, ``ignore``, ``strict``, optional The error handling scheme to use for handling parsing errors. ...
python
{ "resource": "" }
q233220
DS9Parser.set_coordsys
train
def set_coordsys(self, coordsys): """ Transform coordinate system # TODO: needs expert attention """ if coordsys in self.coordsys_mapping: self.coordsys = self.coordsys_mapping[coordsys] else: self.coordsys = coordsys
python
{ "resource": "" }
q233221
DS9Parser.run
train
def run(self): """ Run all steps """ for line_ in self.region_string.split('\n'): for line in line_.split(";"): self.parse_line(line) log.debug('Global state: {}'.format(self))
python
{ "resource": "" }
q233222
DS9Parser.parse_meta
train
def parse_meta(meta_str): """ Parse the metadata for a single ds9 region string. Parameters ---------- meta_str : `str` Meta string, the metadata is everything after the close-paren of the region coordinate specification. All metadata is specified as ...
python
{ "resource": "" }
q233223
DS9Parser.parse_region
train
def parse_region(self, include, region_type, region_end, line): """ Extract a Shape from a region string """ if self.coordsys is None: raise DS9RegionParserError("No coordinate system specified and a" " region has been found.") e...
python
{ "resource": "" }
q233224
DS9RegionParser.parse
train
def parse(self): """ Convert line to shape object """ log.debug(self) self.parse_composite() self.split_line() self.convert_coordinates() self.convert_meta() self.make_shape() log.debug(self)
python
{ "resource": "" }
q233225
DS9RegionParser.split_line
train
def split_line(self): """ Split line into coordinates and meta string """ # coordinate of the # symbol or end of the line (-1) if not found hash_or_end = self.line.find("#") temp = self.line[self.region_end:hash_or_end].strip(" |") self.coord_str = regex_paren.sub...
python
{ "resource": "" }
q233226
DS9RegionParser.convert_coordinates
train
def convert_coordinates(self): """ Convert coordinate string to objects """ coord_list = [] # strip out "null" elements, i.e. ''. It might be possible to eliminate # these some other way, i.e. with regex directly, but I don't know how. # We need to copy in order ...
python
{ "resource": "" }
q233227
DS9RegionParser.convert_meta
train
def convert_meta(self): """ Convert meta string to dict """ meta_ = DS9Parser.parse_meta(self.meta_str) self.meta = copy.deepcopy(self.global_meta) self.meta.update(meta_) # the 'include' is not part of the metadata string; # it is pre-parsed as part of th...
python
{ "resource": "" }
q233228
PixCoord._validate
train
def _validate(val, name, expected='any'): """Validate that a given object is an appropriate `PixCoord`. This is used for input validation throughout the regions package, especially in the `__init__` method of pixel region classes. Parameters ---------- val : `PixCoord` ...
python
{ "resource": "" }
q233229
PixCoord.to_sky
train
def to_sky(self, wcs, origin=_DEFAULT_WCS_ORIGIN, mode=_DEFAULT_WCS_MODE): """Convert this `PixCoord` to `~astropy.coordinates.SkyCoord`. Calls :meth:`astropy.coordinates.SkyCoord.from_pixel`. See parameter description there. """ return SkyCoord.from_pixel( xp=self.x...
python
{ "resource": "" }
q233230
PixCoord.from_sky
train
def from_sky(cls, skycoord, wcs, origin=_DEFAULT_WCS_ORIGIN, mode=_DEFAULT_WCS_MODE): """Create `PixCoord` from `~astropy.coordinates.SkyCoord`. Calls :meth:`astropy.coordinates.SkyCoord.to_pixel`. See parameter description there. """ x, y = skycoord.to_pixel(wcs=wcs, origin=ori...
python
{ "resource": "" }
q233231
PixCoord.separation
train
def separation(self, other): r"""Separation to another pixel coordinate. This is the two-dimensional cartesian separation :math:`d` with .. math:: d = \sqrt{(x_1 - x_2) ^ 2 + (y_1 - y_2) ^ 2} Parameters ---------- other : `PixCoord` Other pixel ...
python
{ "resource": "" }
q233232
skycoord_to_pixel_scale_angle
train
def skycoord_to_pixel_scale_angle(skycoord, wcs, small_offset=1 * u.arcsec): """ Convert a set of SkyCoord coordinates into pixel coordinates, pixel scales, and position angles. Parameters ---------- skycoord : `~astropy.coordinates.SkyCoord` Sky coordinates wcs : `~astropy.wcs.WCS`...
python
{ "resource": "" }
q233233
assert_angle
train
def assert_angle(name, q): """ Check that ``q`` is an angular `~astropy.units.Quantity`. """ if isinstance(q, u.Quantity): if q.unit.physical_type == 'angle': pass else: raise ValueError("{0} should have angular units".format(name)) else: raise TypeErr...
python
{ "resource": "" }
q233234
_silence
train
def _silence(): """A context manager that silences sys.stdout and sys.stderr.""" old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = _DummyFile() sys.stderr = _DummyFile() exception_occurred = False try: yield except: exception_occurred = True # Go ahead...
python
{ "resource": "" }
q233235
use_astropy_helpers
train
def use_astropy_helpers(**kwargs): """ Ensure that the `astropy_helpers` module is available and is importable. This supports automatic submodule initialization if astropy_helpers is included in a project as a git submodule, or will download it from PyPI if necessary. Parameters ---------- ...
python
{ "resource": "" }
q233236
_Bootstrapper.config
train
def config(self): """ A `dict` containing the options this `_Bootstrapper` was configured with. """ return dict((optname, getattr(self, optname)) for optname, _ in CFG_OPTIONS if hasattr(self, optname))
python
{ "resource": "" }
q233237
_Bootstrapper.get_local_directory_dist
train
def get_local_directory_dist(self): """ Handle importing a vendored package from a subdirectory of the source distribution. """ if not os.path.isdir(self.path): return log.info('Attempting to import astropy_helpers from {0} {1!r}'.format( 's...
python
{ "resource": "" }
q233238
_Bootstrapper.get_local_file_dist
train
def get_local_file_dist(self): """ Handle importing from a source archive; this also uses setup_requires but points easy_install directly to the source archive. """ if not os.path.isfile(self.path): return log.info('Attempting to unpack and import astropy_he...
python
{ "resource": "" }
q233239
_Bootstrapper._directory_import
train
def _directory_import(self): """ Import astropy_helpers from the given path, which will be added to sys.path. Must return True if the import succeeded, and False otherwise. """ # Return True on success, False on failure but download is allowed, and # otherwise r...
python
{ "resource": "" }
q233240
_Bootstrapper._check_submodule
train
def _check_submodule(self): """ Check if the given path is a git submodule. See the docstrings for ``_check_submodule_using_git`` and ``_check_submodule_no_git`` for further details. """ if (self.path is None or (os.path.exists(self.path) and not os.path...
python
{ "resource": "" }
q233241
sdot
train
def sdot( U, V ): ''' Computes the tensorproduct reducing last dimensoin of U with first dimension of V. For matrices, it is equal to regular matrix product. ''' nu = U.ndim #nv = V.ndim return np.tensordot( U, V, axes=(nu-1,0) )
python
{ "resource": "" }
q233242
SmolyakBasic.set_values
train
def set_values(self,x): """ Updates self.theta parameter. No returns values""" x = numpy.atleast_2d(x) x = x.real # ahem C_inv = self.__C_inv__ theta = numpy.dot( x, C_inv ) self.theta = theta return theta
python
{ "resource": "" }
q233243
tauchen
train
def tauchen(N, mu, rho, sigma, m=2): """ Approximate an AR1 process by a finite markov chain using Tauchen's method. :param N: scalar, number of nodes for Z :param mu: scalar, unconditional mean of process :param rho: scalar :param sigma: scalar, std. dev. of epsilons :param m: max +- std. ...
python
{ "resource": "" }
q233244
rouwenhorst
train
def rouwenhorst(rho, sigma, N): """ Approximate an AR1 process by a finite markov chain using Rouwenhorst's method. :param rho: autocorrelation of the AR1 process :param sigma: conditional standard deviation of the AR1 process :param N: number of states :return [nodes, P]: equally spaced nodes ...
python
{ "resource": "" }
q233245
tensor_markov
train
def tensor_markov( *args ): """Computes the product of two independent markov chains. :param m1: a tuple containing the nodes and the transition matrix of the first chain :param m2: a tuple containing the nodes and the transition matrix of the second chain :return: a tuple containing the nodes and the ...
python
{ "resource": "" }
q233246
dynare_import
train
def dynare_import(filename,full_output=False, debug=False): '''Imports model defined in specified file''' import os basename = os.path.basename(filename) fname = re.compile('(.*)\.(.*)').match(basename).group(1) f = open(filename) txt = f.read() model = parse_dynare_text(txt,full_output=full...
python
{ "resource": "" }
q233247
_shocks_to_epsilons
train
def _shocks_to_epsilons(model, shocks, T): """ Helper function to support input argument `shocks` being one of many different data types. Will always return a `T, n_e` matrix. """ n_e = len(model.calibration['exogenous']) # if we have a DataFrame, convert it to a dict and rely on the method bel...
python
{ "resource": "" }
q233248
clear_all
train
def clear_all(): """ Clears all parameters, variables, and shocks defined previously """ frame = inspect.currentframe().f_back try: if frame.f_globals.get('variables_order'): # we should avoid to declare symbols twice ! del frame.f_globals['variables_order'] ...
python
{ "resource": "" }
q233249
nonlinear_system
train
def nonlinear_system(model, initial_dr=None, maxit=10, tol=1e-8, grid={}, distribution={}, verbose=True): ''' Finds a global solution for ``model`` by solving one large system of equations using a simple newton algorithm. Parameters ---------- model: NumericModel "dtcscc" model to be ...
python
{ "resource": "" }
q233250
gauss_hermite_nodes
train
def gauss_hermite_nodes(orders, sigma, mu=None): ''' Computes the weights and nodes for Gauss Hermite quadrature. Parameters ---------- orders : int, list, array The order of integration used in the quadrature routine sigma : array-like If one dimensional, the variance of the no...
python
{ "resource": "" }
q233251
newton
train
def newton(f, x, verbose=False, tol=1e-6, maxit=5, jactype='serial'): """Solve nonlinear system using safeguarded Newton iterations Parameters ---------- Return ------ """ if verbose: print = lambda txt: old_print(txt) else: print = lambda txt: None it = 0 e...
python
{ "resource": "" }
q233252
qzordered
train
def qzordered(A,B,crit=1.0): "Eigenvalues bigger than crit are sorted in the top-left." TOL = 1e-10 def select(alpha, beta): return alpha**2>crit*beta**2 [S,T,alpha,beta,U,V] = ordqz(A,B,output='real',sort=select) eigval = abs(numpy.diag(S)/numpy.diag(T)) return [S,T,U,V,eigval]
python
{ "resource": "" }
q233253
ordqz
train
def ordqz(A, B, sort='lhp', output='real', overwrite_a=False, overwrite_b=False, check_finite=True): """ QZ decomposition for a pair of matrices with reordering. .. versionadded:: 0.17.0 Parameters ---------- A : (N, N) array_like 2d array to decompose B : (N, N) array_li...
python
{ "resource": "" }
q233254
parameterized_expectations_direct
train
def parameterized_expectations_direct(model, verbose=False, initial_dr=None, pert_order=1, grid={}, distribution={}, maxit=100, tol=1e-8): ''' Finds a global solution for ``model`` using parameterized expectations function. Requires...
python
{ "resource": "" }
q233255
numdiff
train
def numdiff(fun, args): """Vectorized numerical differentiation""" # vectorized version epsilon = 1e-8 args = list(args) v0 = fun(*args) N = v0.shape[0] l_v = len(v0) dvs = [] for i, a in enumerate(args): l_a = (a).shape[1] dv = numpy.zeros((N, l_v, l_a)) na...
python
{ "resource": "" }
q233256
bandpass_filter
train
def bandpass_filter(data, k, w1, w2): """ This function will apply a bandpass filter to data. It will be kth order and will select the band between w1 and w2. Parameters ---------- data: array, dtype=float The data you wish to filter k: number, int The order ...
python
{ "resource": "" }
q233257
dprint
train
def dprint(s): '''Prints `s` with additional debugging informations''' import inspect frameinfo = inspect.stack()[1] callerframe = frameinfo.frame d = callerframe.f_locals if (isinstance(s,str)): val = eval(s, d) else: val = s cc = frameinfo.code_context[0] ...
python
{ "resource": "" }
q233258
non_decreasing_series
train
def non_decreasing_series(n, size): '''Lists all combinations of 0,...,n-1 in increasing order''' if size == 1: return [[a] for a in range(n)] else: lc = non_decreasing_series(n, size-1) ll = [] for l in lc: last = l[-1] for i in range(last, n): ...
python
{ "resource": "" }
q233259
higher_order_diff
train
def higher_order_diff(eqs, syms, order=2): '''Takes higher order derivatives of a list of equations w.r.t a list of paramters''' import numpy eqs = list([sympy.sympify(eq) for eq in eqs]) syms = list([sympy.sympify(s) for s in syms]) neq = len(eqs) p = len(syms) D = [numpy.array(eqs)] ...
python
{ "resource": "" }
q233260
get_ranked_players
train
def get_ranked_players(): """Get the list of the first 100 ranked players.""" rankings_page = requests.get(RANKINGS_URL) root = etree.HTML(rankings_page.text) player_rows = root.xpath('//div[@id="ranked"]//tr') for row in player_rows[1:]: player_row = row.xpath('td[@class!="country"]//text...
python
{ "resource": "" }
q233261
Rank.difference
train
def difference(cls, first, second): """Tells the numerical difference between two ranks.""" # so we always get a Rank instance even if string were passed in first, second = cls(first), cls(second) rank_list = list(cls) return abs(rank_list.index(first) - rank_list.index(second))
python
{ "resource": "" }
q233262
_CardMeta.make_random
train
def make_random(cls): """Returns a random Card instance.""" self = object.__new__(cls) self.rank = Rank.make_random() self.suit = Suit.make_random() return self
python
{ "resource": "" }
q233263
twoplustwo_player
train
def twoplustwo_player(username): """Get profile information about a Two plus Two Forum member given the username.""" from .website.twoplustwo import ForumMember, AmbiguousUserNameError, UserNotFoundError try: member = ForumMember(username) except UserNotFoundError: raise click.ClickExc...
python
{ "resource": "" }
q233264
p5list
train
def p5list(num): """List pocketfives ranked players, max 100 if no NUM, or NUM if specified.""" from .website.pocketfives import get_ranked_players format_str = '{:>4.4} {!s:<15.13}{!s:<18.15}{!s:<9.6}{!s:<10.7}'\ '{!s:<14.11}{!s:<12.9}{!s:<12.9}{!s:<12.9}{!s:<4.4}' click.echo(form...
python
{ "resource": "" }
q233265
psstatus
train
def psstatus(): """Shows PokerStars status such as number of players, tournaments.""" from .website.pokerstars import get_status _print_header('PokerStars status') status = get_status() _print_values( ('Info updated', status.updated), ('Tables', status.tables), ('Players', ...
python
{ "resource": "" }
q233266
Notes.notes
train
def notes(self): """Tuple of notes..""" return tuple(self._get_note_data(note) for note in self.root.iter('note'))
python
{ "resource": "" }
q233267
Notes.labels
train
def labels(self): """Tuple of labels.""" return tuple(_Label(label.get('id'), label.get('color'), label.text) for label in self.root.iter('label'))
python
{ "resource": "" }
q233268
Notes.add_note
train
def add_note(self, player, text, label=None, update=None): """Add a note to the xml. If update param is None, it will be the current time.""" if label is not None and (label not in self.label_names): raise LabelNotFoundError('Invalid label: {}'.format(label)) if update is None: ...
python
{ "resource": "" }
q233269
Notes.append_note
train
def append_note(self, player, text): """Append text to an already existing note.""" note = self._find_note(player) note.text += text
python
{ "resource": "" }
q233270
Notes.prepend_note
train
def prepend_note(self, player, text): """Prepend text to an already existing note.""" note = self._find_note(player) note.text = text + note.text
python
{ "resource": "" }
q233271
Notes.get_label
train
def get_label(self, name): """Find the label by name.""" label_tag = self._find_label(name) return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
python
{ "resource": "" }
q233272
Notes.add_label
train
def add_label(self, name, color): """Add a new label. It's id will automatically be calculated.""" color_upper = color.upper() if not self._color_re.match(color_upper): raise ValueError('Invalid color: {}'.format(color)) labels_tag = self.root[0] last_id = int(labels...
python
{ "resource": "" }
q233273
Notes.del_label
train
def del_label(self, name): """Delete a label by name.""" labels_tag = self.root[0] labels_tag.remove(self._find_label(name))
python
{ "resource": "" }
q233274
Notes.save
train
def save(self, filename): """Save the note XML to a file.""" with open(filename, 'w') as fp: fp.write(str(self))
python
{ "resource": "" }
q233275
_BaseHandHistory.board
train
def board(self): """Calculates board from flop, turn and river.""" board = [] if self.flop: board.extend(self.flop.cards) if self.turn: board.append(self.turn) if self.river: board.append(self.river) return tuple...
python
{ "resource": "" }
q233276
_BaseHandHistory._parse_date
train
def _parse_date(self, date_string): """Parse the date_string and return a datetime object as UTC.""" date = datetime.strptime(date_string, self._DATE_FORMAT) self.date = self._TZ.localize(date).astimezone(pytz.UTC)
python
{ "resource": "" }
q233277
_SplittableHandHistoryMixin._split_raw
train
def _split_raw(self): """Split hand history by sections.""" self._splitted = self._split_re.split(self.raw) # search split locations (basically empty strings) self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem]
python
{ "resource": "" }
q233278
ForumMember._get_timezone
train
def _get_timezone(self, root): """Find timezone informatation on bottom of the page.""" tz_str = root.xpath('//div[@class="smallfont" and @align="center"]')[0].text hours = int(self._tz_re.search(tz_str).group(1)) return tzoffset(tz_str, hours * 60)
python
{ "resource": "" }
q233279
get_current_tournaments
train
def get_current_tournaments(): """Get the next 200 tournaments from pokerstars.""" schedule_page = requests.get(TOURNAMENTS_XML_URL) root = etree.XML(schedule_page.content) for tour in root.iter('{*}tournament'): yield _Tournament( start_date=tour.findtext('{*}start_date'), ...
python
{ "resource": "" }
q233280
_filter_file
train
def _filter_file(src, dest, subst): """Copy src to dest doing substitutions on the fly. """ substre = re.compile(r'\$(%s)' % '|'.join(subst.keys())) def repl(m): return subst[m.group(1)] with open(src, "rt") as sf, open(dest, "wt") as df: while True: l = sf.readline() ...
python
{ "resource": "" }
q233281
BaseEndpoint._fixup_graphql_error
train
def _fixup_graphql_error(self, data): '''Given a possible GraphQL error payload, make sure it's in shape. This will ensure the given ``data`` is in the shape: .. code-block:: json {"errors": [{"message": "some string"}]} If ``errors`` is not an array, it will be made into ...
python
{ "resource": "" }
q233282
BaseEndpoint.snippet
train
def snippet(code, locations, sep=' | ', colmark=('-', '^'), context=5): '''Given a code and list of locations, convert to snippet lines. return will include line number, a separator (``sep``), then line contents. At most ``context`` lines are shown before each location line. A...
python
{ "resource": "" }
q233283
_create_non_null_wrapper
train
def _create_non_null_wrapper(name, t): 'creates type wrapper for non-null of given type' def __new__(cls, json_data, selection_list=None): if json_data is None: raise ValueError(name + ' received null value') return t(json_data, selection_list) def __to_graphql_input__(value, in...
python
{ "resource": "" }
q233284
_create_list_of_wrapper
train
def _create_list_of_wrapper(name, t): 'creates type wrapper for list of given type' def __new__(cls, json_data, selection_list=None): if json_data is None: return None return [t(v, selection_list) for v in json_data] def __to_graphql_input__(value, indent=0, indent_string=' '):...
python
{ "resource": "" }
q233285
add_query_to_url
train
def add_query_to_url(url, extra_query): '''Adds an extra query to URL, returning the new URL. Extra query may be a dict or a list as returned by :func:`urllib.parse.parse_qsl()` and :func:`urllib.parse.parse_qs()`. ''' split = urllib.parse.urlsplit(url) merged_query = urllib.parse.parse_qsl(sp...
python
{ "resource": "" }
q233286
connection_args
train
def connection_args(*lst, **mapping): '''Returns the default parameters for connection. Extra parameters may be given as argument, both as iterable, positional tuples or mapping. By default, provides: - ``after: String`` - ``before: String`` - ``first: Int`` - ``last: Int`` ''...
python
{ "resource": "" }
q233287
msjd
train
def msjd(theta): """Mean squared jumping distance. """ s = 0. for p in theta.dtype.names: s += np.sum(np.diff(theta[p], axis=0) ** 2) return s
python
{ "resource": "" }
q233288
StaticModel.loglik
train
def loglik(self, theta, t=None): """ log-likelihood at given parameter values. Parameters ---------- theta: dict-like theta['par'] is a ndarray containing the N values for parameter par t: int time (if set to None, the full log-likelihood is returned) ...
python
{ "resource": "" }
q233289
StaticModel.logpost
train
def logpost(self, theta, t=None): """Posterior log-density at given parameter values. Parameters ---------- theta: dict-like theta['par'] is a ndarray containing the N values for parameter par t: int time (if set to None, the full posterior is returned)...
python
{ "resource": "" }
q233290
FancyList.copyto
train
def copyto(self, src, where=None): """ Same syntax and functionality as numpy.copyto """ for n, _ in enumerate(self.l): if where[n]: self.l[n] = src.l[n]
python
{ "resource": "" }
q233291
ThetaParticles.copy
train
def copy(self): """Returns a copy of the object.""" attrs = {k: self.__dict__[k].copy() for k in self.containers} attrs.update({k: cp.deepcopy(self.__dict__[k]) for k in self.shared}) return self.__class__(**attrs)
python
{ "resource": "" }
q233292
ThetaParticles.copyto
train
def copyto(self, src, where=None): """Emulates function `copyto` in NumPy. Parameters ---------- where: (N,) bool ndarray True if particle n in src must be copied. src: (N,) `ThetaParticles` object source for each n such that where[n] is True, cop...
python
{ "resource": "" }
q233293
ThetaParticles.copyto_at
train
def copyto_at(self, n, src, m): """Copy to at a given location. Parameters ---------- n: int index where to copy src: `ThetaParticles` object source m: int index of the element to be copied Note ---- Basical...
python
{ "resource": "" }
q233294
MetroParticles.Metropolis
train
def Metropolis(self, compute_target, mh_options): """Performs a certain number of Metropolis steps. Parameters ---------- compute_target: function computes the target density for the proposed values mh_options: dict + 'type_prop': {'random_walk', 'inde...
python
{ "resource": "" }
q233295
BaumWelch.backward
train
def backward(self): """Backward recursion. Upon completion, the following list of length T is available: * smth: marginal smoothing probabilities Note ---- Performs the forward step in case it has not been performed before. """ if not self.filt: ...
python
{ "resource": "" }
q233296
predict_step
train
def predict_step(F, covX, filt): """Predictive step of Kalman filter. Parameters ---------- F: (dx, dx) numpy array Mean of X_t | X_{t-1} is F * X_{t-1} covX: (dx, dx) numpy array covariance of X_t | X_{t-1} filt: MeanAndCov object filtering distribution at time t-1 ...
python
{ "resource": "" }
q233297
filter_step
train
def filter_step(G, covY, pred, yt): """Filtering step of Kalman filter. Parameters ---------- G: (dy, dx) numpy array mean of Y_t | X_t is G * X_t covX: (dx, dx) numpy array covariance of Y_t | X_t pred: MeanAndCov object predictive distribution at time t Returns ...
python
{ "resource": "" }
q233298
MVLinearGauss.check_shapes
train
def check_shapes(self): """ Check all dimensions are correct. """ assert self.covX.shape == (self.dx, self.dx), error_msg assert self.covY.shape == (self.dy, self.dy), error_msg assert self.F.shape == (self.dx, self.dx), error_msg assert self.G.shape == (self.dy, ...
python
{ "resource": "" }
q233299
sobol
train
def sobol(N, dim, scrambled=1): """ Sobol sequence. Parameters ---------- N : int length of sequence dim: int dimension scrambled: int which scrambling method to use: + 0: no scrambling + 1: Owen's scrambling + 2: Faure-Tezuka ...
python
{ "resource": "" }