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 get_header_example(cls, header): """ Get example for header object :param Header header: Header object :return: example :rtype: dict """
if header.is_array: result = cls.get_example_for_array(header.item) else: example_method = getattr(cls, '{}_example'.format(header.type)) result = example_method(header.properties, header.type_format) return {header.name: result}
<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_property_example(cls, property_, nested=None, **kw): """ Get example for property :param dict property_: :param set nested: :return: example value """
paths = kw.get('paths', []) name = kw.get('name', '') result = None if name and paths: paths = list(map(lambda path: '.'.join((path, name)), paths)) result, path = cls._get_custom_example(paths) if result is not None and property_['type'] in PRIMITIVE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkres(self): """ Create a directory tree for the resized assets """
for d in DENSITY_TYPES: if d == 'ldpi' and not self.ldpi: continue # skip ldpi if d == 'xxxhdpi' and not self.xxxhdpi: continue # skip xxxhdpi try: path = os.path.join(self.out, 'res/drawable-%s' % d) os.make...
<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_size_for_density(self, size, target_density): """ Return the new image size for the target density """
current_size = size current_density = DENSITY_MAP[self.source_density] target_density = DENSITY_MAP[target_density] return int(current_size * (target_density / current_density))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resize_image(self, path, im): """ Generate assets from the given image and path in case you've already called Image.open """
# Get the original filename _, filename = os.path.split(path) # Generate the new filename filename = self.get_safe_filename(filename) filename = '%s%s' % (self.prefix if self.prefix else '', filename) # Get the original image size w, h = im.size # Gene...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self, message, callback_arg=None): """message should be a dict recognized by the Stitch Import API. See https://www.stitchdata.com/docs/integrations/imp...
if message['action'] == 'upsert': message.setdefault('key_names', self.key_names) message['client_id'] = self.client_id message.setdefault('table_name', self.table_name) self._add_message(message, callback_arg) batch = self._take_batch(self.target_messages_per_ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _take_batch(self, min_records): '''If we have enough data to build a batch, returns all the data in the buffer and then clears the buffer.''' if not self._buffer: return [] enough_messages = len(self._buffer) >= min_records enough_time = time.time() - self.time_...
<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_parameters_by_location(self, locations=None, excludes=None): """ Get parameters list by location :param locations: list of locations :type locations: lis...
result = self.parameters if locations: result = filter(lambda x: x.location_in in locations, result) if excludes: result = filter(lambda x: x.location_in not in excludes, result) return list(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def body(self): """ Return body request parameter :return: Body parameter :rtype: Parameter or None """
body = self.get_parameters_by_location(['body']) return self.root.schemas.get(body[0].type) if body else 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 text_to_edtf(text): """ Generate EDTF string equivalent of a given natural language date string. """
if not text: return t = text.lower() # try parsing the whole thing result = text_to_edtf_date(t) if not result: # split by list delims and move fwd with the first thing that returns a non-empty string. # TODO: assemble multiple dates into a {} or [] structure. for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(node): """Find current canonical representative equivalent to node. Adjust the parent pointer of each node along the way to the root to point directly a...
if node.parent is None: return node root = node while root.parent is not None: root = root.parent parent = node while parent.parent is not root: grandparent = parent.parent parent.parent = root parent = grandparent return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classes(equivalences): """Compute mapping from element to list of equivalent elements. `equivalences` is an iterable of (x, y) tuples representing equivalenc...
node = OrderedDict() def N(x): if x in node: return node[x] n = node[x] = Node(x) return n for x, y in equivalences: union(N(x), N(y)) eqclass = OrderedDict() for x, n in node.iteritems(): x_ = find(n).element if x_ not in eqclass: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def changebase(string, frm, to, minlen=0): """ Change a string's characters from one base to another. Return the re-encoded string """
if frm == to: return lpad(string, get_code_string(frm)[0], minlen) return encode(decode(string, frm), to, minlen)
<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_CrossCatClient(client_type, **kwargs): """Helper which instantiates the appropriate Engine and returns a Client"""
client = None if client_type == 'local': import crosscat.LocalEngine as LocalEngine le = LocalEngine.LocalEngine(**kwargs) client = CrossCatClient(le) elif client_type == 'multiprocessing': import crosscat.MultiprocessingEngine as MultiprocessingEngine me = Multip...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _serialize(xp_ast): '''Generate token strings which, when joined together, form a valid XPath serialization of the AST.''' if hasattr(xp_ast, '_serialize'): for tok in xp_ast._serialize(): yield tok elif isinstance(xp_ast, string_types): # strings in serialized xpath nee...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(python=PYTHON): """Build the bigfloat library for in-place testing."""
clean() local( "LIBRARY_PATH={library_path} CPATH={include_path} {python} " "setup.py build_ext --inplace".format( library_path=LIBRARY_PATH, include_path=INCLUDE_PATH, python=python, ))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(python=PYTHON): """Install into site-packages"""
local( "LIBRARY_PATH={library_path} CPATH={include_path} {python} " "setup.py build".format( library_path=LIBRARY_PATH, include_path=INCLUDE_PATH, python=python, )) local("sudo {python} setup.py install".format(python=python))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uninstall(python=PYTHON): """Uninstall from site-packages"""
site_packages = local( "{python} -c 'from distutils.sysconfig import " "get_python_lib; print(get_python_lib())'".format(python=python), capture=True, ) with lcd(site_packages): local("sudo rm mpfr.so") local("sudo rm -fr bigfloat") local("sudo rm bigfloat*.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 sync_virtualchain(blockchain_opts, last_block, state_engine, expected_snapshots={}, tx_filter=None ): """ Synchronize the virtual blockchain state up until a...
rc = False start = datetime.datetime.now() while True: try: # advance state rc = indexer.StateEngine.build(blockchain_opts, last_block + 1, state_engine, expected_snapshots=expected_snapshots, tx_filter=tx_filter ) break except Exception, 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 virtualchain_set_opfields( op, **fields ): """ Pass along virtualchain-reserved fields to a virtualchain operation. This layer of indirection is meant to hel...
# warn about unsupported fields for f in fields.keys(): if f not in indexer.RESERVED_KEYS: log.warning("Unsupported virtualchain field '%s'" % f) # propagate reserved fields for f in fields.keys(): if f in indexer.RESERVED_KEYS: op[f] = fields[f] return op
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ascii2h5(dirname, output_fname): """ Converts from a directory of tarballed ASCII ".samp" files to a single HDF5 file. Essentially, converts from the origina...
import tarfile import sys from glob import glob from contextlib import closing # The datatype that will be used to store extinction, A0 A0_dtype = 'float16' def load_samp_file(f, fname): # Parse filename fname_chunks = os.path.split(fname)[1].split('_') l = float(...
<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_dihedral(self, construction_table): """Checks, if the dihedral defining atom is colinear. Checks for each index starting from the third row of the ``co...
c_table = construction_table angles = self.get_angle_degrees(c_table.iloc[3:, :].values) problem_index = np.nonzero((175 < angles) | (angles < 5))[0] rename = dict(enumerate(c_table.index[3:])) problem_index = [rename[i] for i in problem_index] return problem_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correct_dihedral(self, construction_table, use_lookup=None): """Reindexe the dihedral defining atom if linear reference is used. Uses :meth:`~Cartesian.check...
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] problem_index = self.check_dihedral(construction_table) bond_dict = self._give_val_sorted_bond_dict(use_lookup=use_lookup) c_table = construction_table.copy() for i in problem_index: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _has_valid_abs_ref(self, i, construction_table): """Checks, if ``i`` uses valid absolute references. Checks for each index from first to third row of the ``c...
c_table = construction_table abs_refs = constants.absolute_refs A = np.empty((3, 3)) row = c_table.index.get_loc(i) if row > 2: message = 'The index {i} is not from the first three, rows'.format raise ValueError(message(i=i)) for k in range(3): ...
<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_absolute_refs(self, construction_table): """Checks first three rows of ``construction_table`` for linear references Checks for each index from first to...
c_table = construction_table problem_index = [i for i in c_table.index[:3] if not self._has_valid_abs_ref(i, c_table)] return problem_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correct_absolute_refs(self, construction_table): """Reindexe construction_table if linear reference in first three rows present. Uses :meth:`~Cartesian.check...
c_table = construction_table.copy() abs_refs = constants.absolute_refs problem_index = self.check_absolute_refs(c_table) for i in problem_index: order_of_refs = iter(permutations(abs_refs.keys())) finished = False while not finished: i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_zmat(self, construction_table): """Create the Zmatrix from a construction table. Args: Construction table (pd.DataFrame): Returns: Zmat: A new instan...
c_table = construction_table default_cols = ['atom', 'b', 'bond', 'a', 'angle', 'd', 'dihedral'] optional_cols = list(set(self.columns) - {'atom', 'x', 'y', 'z'}) zmat_frame = pd.DataFrame(columns=default_cols + optional_cols, dtype='float', index=c_ta...
<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_zmat(self, construction_table=None, use_lookup=None): """Transform to internal coordinates. Transforming to internal coordinates involves basically three...
if use_lookup is None: use_lookup = settings['defaults']['use_lookup'] self.get_bonds(use_lookup=use_lookup) self._give_val_sorted_bond_dict(use_lookup=use_lookup) use_lookup = True # During function execution the connectivity situation won't change # So use...
<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_grad_zmat(self, construction_table, as_function=True): r"""Return the gradient for the transformation to a Zmatrix. If ``as_function`` is True, a functio...
if (construction_table.index != self.index).any(): message = "construction_table and self must use the same index" raise ValueError(message) c_table = construction_table.loc[:, ['b', 'a', 'd']] c_table = c_table.replace(constants.int_label) c_table = c_table.repl...
<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_data(self, new_cols=None): """Adds a column with the requested data. If you want to see for example the mass, the colormap used in jmol and the block of ...
atoms = self['atom'] data = constants.elements if pd.api.types.is_list_like(new_cols): new_cols = set(new_cols) elif new_cols is None: new_cols = set(data.columns) else: new_cols = [new_cols] new_frame = data.loc[atoms, set(new_cols) -...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_same_sumformula(self, other): """Determines if ``other`` has the same sumformula Args: other (molecule): Returns: bool: """
same_atoms = True for atom in set(self['atom']): own_atom_number = len(self[self['atom'] == atom]) other_atom_number = len(other[other['atom'] == atom]) same_atoms = (own_atom_number == other_atom_number) if not same_atoms: break r...
<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_electron_number(self, charge=0): """Return the number of electrons. Args: charge (int): Charge of the molecule. Returns: int: """
atomic_number = constants.elements['atomic_number'].to_dict() return sum([atomic_number[atom] for atom in self['atom']]) - charge
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def support_jsonp(api_instance, callback_name_source='callback'): """Let API instance can respond jsonp request automatically. `callback_name_source` can be a st...
output_json = api_instance.representations['application/json'] @api_instance.representation('application/json') def handle_jsonp(data, code, headers=None): resp = output_json(data, code, headers) if code == 200: callback = request.args.get(callback_name_source, False) if not c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insert(self, loc, column, value, allow_duplicates=False, inplace=False): """Insert column into molecule at specified location. Wrapper around the :meth:`pand...
out = self if inplace else self.copy() out._frame.insert(loc, column, value, allow_duplicates=allow_duplicates) if not inplace: return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_multisig_segwit_info( m, pks ): """ Make either a p2sh-p2wpkh or p2sh-p2wsh redeem script and p2sh address. Return {'address': p2sh address, 'redeem_scr...
pubs = [] privkeys = [] for pk in pks: priv = BitcoinPrivateKey(pk, compressed=True) priv_hex = priv.to_hex() pub_hex = priv.public_key().to_hex() privkeys.append(priv_hex) pubs.append(keylib.key_formatting.compress(pub_hex)) script = None if len(pubs) == ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_multisig_wallet( m, n ): """ Create a bundle of information that can be used to generate an m-of-n multisig scriptsig. """
if m <= 1 and n <= 1: raise ValueError("Invalid multisig parameters") pks = [] for i in xrange(0, n): pk = BitcoinPrivateKey(compressed=True).to_wif() pks.append(pk) return make_multisig_info( m, pks )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_segwit_info(privkey=None): """ Create a bundle of information that can be used to generate a p2sh-p2wpkh transaction """
if privkey is None: privkey = BitcoinPrivateKey(compressed=True).to_wif() return make_multisig_segwit_info(1, [privkey])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_multisig_segwit_wallet( m, n ): """ Create a bundle of information that can be used to generate an m-of-n multisig witness script. """
pks = [] for i in xrange(0, n): pk = BitcoinPrivateKey(compressed=True).to_wif() pks.append(pk) return make_multisig_segwit_info(m, pks)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resources_preparing_factory(app, wrapper): """ Factory which wrap all resources in settings. """
settings = app.app.registry.settings config = settings.get(CONFIG_RESOURCES, None) if not config: return resources = [(k, [wrapper(r, GroupResource(k, v)) for r in v]) for k, v in config] settings[CONFIG_RESOURCES] = resources
<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_tx_fee_per_byte(bitcoind_opts=None, config_path=None, bitcoind_client=None): """ Get the tx fee per byte from the underlying blockchain Return the fee on...
if bitcoind_client is None: bitcoind_client = get_bitcoind_client(bitcoind_opts=bitcoind_opts, config_path=config_path) try: # try to confirm in 2-3 blocks try: fee_info = bitcoind_client.estimatesmartfee(2) if 'errors' in fee_info and len(fee_info['errors']) > ...
<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_tx_fee(tx_hex, config_path=None, bitcoind_opts=None, bitcoind_client=None): """ Get the tx fee for a tx Return the fee on success Return None on error ""...
tx_fee_per_byte = get_tx_fee_per_byte(config_path=config_path, bitcoind_opts=bitcoind_opts, bitcoind_client=bitcoind_client) if tx_fee_per_byte is None: return None return calculate_tx_fee(tx_hex, tx_fee_per_byte)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_error(self, e): """ Resolve the problem about sometimes error message specified by programmer won't output to user. Flask-RESTFul's error handler hand...
if isinstance(e, HTTPException) and not hasattr(e, 'data'): e.data = dict(message=e.description) return super(ErrorHandledApi, self).handle_error(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 main(global_settings, **settings): """Entrypoint for WSGI app."""
my_session_factory = SignedCookieSessionFactory('itsaseekreet') # Add session engine config = Configurator( settings=settings, session_factory=my_session_factory ) # Add static and templates config.add_static_view(name='static', path='static') config.include('pyramid_jinja2'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_schema(uri, path, comment=None): """Download a schema from a specified URI and save it locally. :param uri: url where the schema should be downloade...
# if requests isn't available, warn and bail out if requests is None: sys.stderr.write(req_requests_msg) return # short-hand name of the schema, based on uri schema = os.path.basename(uri) try: req = requests.get(uri, stream=True) req.raise_for_status() wit...
<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_catalog(xsd_schemas=None, xmlcatalog_dir=None, xmlcatalog_file=None): """Generating an XML catalog for use in resolving schemas Creates the XML Cata...
# if requests isn't available, warn and bail out if requests is None: sys.stderr.write(req_requests_msg) return logger.debug("Generating a new XML catalog") if xsd_schemas is None: xsd_schemas = XSD_SCHEMAS if xmlcatalog_file is None: xmlcatalog_file = XMLCATALOG_F...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sqlite3_find_tool(): """ Find the sqlite3 binary Return the path to the binary on success Return None on error """
# find sqlite3 path = os.environ.get("PATH", None) if path is None: path = "/usr/local/bin:/usr/bin:/bin" sqlite3_path = None dirs = path.split(":") for pathdir in dirs: if len(pathdir) == 0: continue sqlite3_path = os.path.join(pathdir, 'sqlite3') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sqlite3_backup(src_path, dest_path): """ Back up a sqlite3 database, while ensuring that no ongoing queries are being executed. Return True on success Return...
# find sqlite3 sqlite3_path = sqlite3_find_tool() if sqlite3_path is None: log.error("Failed to find sqlite3 tool") return False sqlite3_cmd = [sqlite3_path, '{}'.format(src_path), '.backup "{}"'.format(dest_path)] rc = None backoff = 1.0 out = None err = None tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def state_engine_replay_block(existing_state_engine, new_state_engine, block_height, expected_snapshots={}): """ Extract the existing chain state transactions fr...
assert new_state_engine.lastblock + 1 == block_height, 'Block height mismatch: {} + 1 != {}'.format(new_state_engine.lastblock, block_height) db_con = StateEngine.db_open(existing_state_engine.impl, existing_state_engine.working_dir) chainstate_block = existing_state_engine.db_chainstate_get_block(db...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def state_engine_verify(trusted_consensus_hash, consensus_block_height, consensus_impl, untrusted_working_dir, new_state_engine, start_block=None, expected_snapsh...
assert hasattr(consensus_impl, 'get_initial_snapshots') final_consensus_hash = state_engine_replay(consensus_impl, untrusted_working_dir, new_state_engine, consensus_block_height, \ start_block=start_block, initial_snapshots=consensus_impl.get_initial_snapsh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_restore(self, block_number=None): """ Restore the database and clear the indexing lockfile. Restore to a given block if given; otherwise use the most rece...
restored = False if block_number is not None: # restore a specific backup try: self.backup_restore(block_number, self.impl, self.working_dir) restored = True except AssertionError: log.error("Failed to restore state fro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_exists(cls, impl, working_dir): """ Does the chainstate db exist? """
path = config.get_snapshots_filename(impl, working_dir) return os.path.exists(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 db_create(cls, impl, working_dir): """ Create a sqlite3 db at the given path. Create all the tables and indexes we need. Returns a db connection on success R...
global VIRTUALCHAIN_DB_SCRIPT log.debug("Setup chain state in {}".format(working_dir)) path = config.get_snapshots_filename(impl, working_dir) if os.path.exists( path ): raise Exception("Database {} already exists") lines = [l + ";" for l in VIRTUALCHAIN_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 db_connect(cls, path): """ connect to our chainstate db """
con = sqlite3.connect(path, isolation_level=None, timeout=2**30) con.row_factory = StateEngine.db_row_factory return con
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_open(cls, impl, working_dir): """ Open a connection to our chainstate db """
path = config.get_snapshots_filename(impl, working_dir) return cls.db_connect(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 db_query_execute(cls, cur, query, values, verbose=True): """ Execute a query. Handle db timeouts. Abort on failure. """
timeout = 1.0 if verbose: log.debug(cls.db_format_query(query, values)) while True: try: ret = cur.execute(query, values) return ret except sqlite3.OperationalError as oe: if oe.message == "database is locked"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_chainstate_append(cls, cur, **fields): """ Insert a row into the chain state. Meant to be executed as part of a transaction. Return True on success Raise ...
missing = [] extra = [] for reqfield in CHAINSTATE_FIELDS: if reqfield not in fields: missing.append(reqfield) for fieldname in fields: if fieldname not in CHAINSTATE_FIELDS: extra.append(fieldname) if len(missing) > 0 or...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_snapshot_append(cls, cur, block_id, consensus_hash, ops_hash, timestamp): """ Append hash info for the last block processed, and the time at which it was ...
query = 'INSERT INTO snapshots (block_id,consensus_hash,ops_hash,timestamp) VALUES (?,?,?,?);' args = (block_id,consensus_hash,ops_hash,timestamp) cls.db_query_execute(cur, query, args) 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 db_chainstate_get_block(cls, cur, block_height): """ Get the list of virtualchain transactions accepted at a given block. Returns the list of rows, where eac...
query = 'SELECT * FROM chainstate WHERE block_id = ? ORDER BY vtxindex;' args = (block_height,) rows = cls.db_query_execute(cur, query, args, verbose=False) ret = [] for r in rows: rowdata = { 'txid': str(r['txid']), 'block_id': r['b...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_set_indexing(cls, is_indexing, impl, working_dir): """ Set lockfile path as to whether or not the system is indexing. NOT THREAD SAFE, USE ONLY FOR CRASH ...
indexing_lockfile_path = config.get_lockfile_filename(impl, working_dir) if is_indexing: # make sure this exists with open(indexing_lockfile_path, 'w') as f: pass else: # make sure it does not exist try: os.unlink...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_is_indexing(cls, impl, working_dir): """ Is the system indexing? Return True if so, False if not. """
indexing_lockfile_path = config.get_lockfile_filename(impl, working_dir) return os.path.exists(indexing_lockfile_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 get_lastblock(cls, impl, working_dir): """ What was the last block processed? Return the number on success Return None on failure to read """
if not cls.db_exists(impl, working_dir): return None con = cls.db_open(impl, working_dir) query = 'SELECT MAX(block_id) FROM snapshots;' rows = cls.db_query_execute(con, query, (), verbose=False) ret = None for r in rows: ret = r['MAX(bl...
<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_state_paths(cls, impl, working_dir): """ Get the set of state paths that point to the current chain and state info. Returns a list of paths. """
return [config.get_db_filename(impl, working_dir), config.get_snapshots_filename(impl, working_dir)]
<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_backup_blocks(cls, impl, working_dir): """ Get the set of block IDs that were backed up """
ret = [] backup_dir = config.get_backups_directory(impl, working_dir) if not os.path.exists(backup_dir): return [] for name in os.listdir( backup_dir ): if ".bak." not in name: continue suffix = name.split(".bak.")[-1] t...
<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_backup_paths(cls, block_id, impl, working_dir): """ Get the set of backup paths, given the virtualchain implementation module and block number """
backup_dir = config.get_backups_directory(impl, working_dir) backup_paths = [] for p in cls.get_state_paths(impl, working_dir): pbase = os.path.basename(p) backup_path = os.path.join( backup_dir, pbase + (".bak.%s" % block_id)) backup_paths.append( backup_pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backup_restore(cls, block_id, impl, working_dir): """ Restore from a backup, given the virutalchain implementation module and block number. NOT THREAD SAFE. ...
backup_dir = config.get_backups_directory(impl, working_dir) backup_paths = cls.get_backup_paths(block_id, impl, working_dir) for p in backup_paths: assert os.path.exists(p), "No such backup file: {}".format(p) for p in cls.get_state_paths(impl, working_dir): pb...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_backups(self, block_id): """ If we're doing backups on a regular basis, then carry them out here if it is time to do so. This method does nothing otherw...
assert self.setup, "Not set up yet. Call .db_setup() first!" # make a backup? if self.backup_frequency is not None: if (block_id % self.backup_frequency) == 0: backup_dir = config.get_backups_directory(self.impl, self.working_dir) if not os.path.ex...
<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, block_id, consensus_hash, ops_hash, accepted_ops, virtualchain_ops_hints, backup=False): """ Write out all state to the working directory. Calls t...
assert self.setup, "Not set up yet. Call .db_setup() first!" assert len(accepted_ops) == len(virtualchain_ops_hints) if self.read_only: log.error("FATAL: StateEngine is read only") traceback.print_stack() os.abort() if block_id < self.lastblock: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_snapshot_from_ops_hash( cls, record_root_hash, prev_consensus_hashes ): """ Generate the consensus hash from the hash over the current ops, and all prev...
# mix into previous consensus hashes... all_hashes = prev_consensus_hashes[:] + [record_root_hash] all_hashes.sort() all_hashes_merkle_tree = MerkleTree( all_hashes ) root_hash = all_hashes_merkle_tree.root() consensus_hash = StateEngine.calculate_consensus_hash( root_h...
<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_virtualchain_field(cls, opdata, virtualchain_field, value): """ Set a virtualchain field value. Used by implementations that generate extra consensus dat...
assert virtualchain_field in RESERVED_KEYS, 'Invalid field name {} (choose from {})'.format(virtualchain_field, ','.join(RESERVED_KEYS)) opdata[virtualchain_field] = 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 parse_transaction(self, block_id, tx): """ Given a block ID and an data-bearing transaction, try to parse it into a virtual chain operation. Use the implemen...
data_hex = tx['nulldata'] inputs = tx['ins'] outputs = tx['outs'] senders = tx['senders'] fee = tx['fee'] txhex = tx['hex'] merkle_path = tx['tx_merkle_path'] if not is_hex(data_hex): # should always work; the tx downloader c...
<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_block(self, block_id, txs): """ Given the sequence of transactions in a block, turn them into a sequence of virtual chain operations. Return the list o...
ops = [] for i in range(0,len(txs)): tx = txs[i] op = self.parse_transaction(block_id, tx) if op is not None: ops.append( op ) return ops
<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_reserved_keys(self, op): """ Remove reserved keywords from an op dict, which can then safely be passed into the db. Returns a new op dict, and the res...
sanitized = {} reserved = {} for k in op.keys(): if str(k) not in RESERVED_KEYS: sanitized[str(k)] = copy.deepcopy(op[k]) else: reserved[str(k)] = copy.deepcopy(op[k]) return sanitized, reserved
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_accept(self, block_id, vtxindex, opcode, op_data): """ Log an accepted operation """
log.debug("ACCEPT op {} at ({}, {}) ({})".format(opcode, block_id, vtxindex, json.dumps(op_data, sort_keys=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 process_ops(self, block_id, ops): """ Given a transaction-ordered sequence of parsed operations, check their validity and give them to the state engine to af...
new_ops = defaultdict(list) for op in self.opcodes: new_ops[op] = [] # transaction-ordered listing of accepted operations new_ops['virtualchain_ordered'] = [] new_ops['virtualchain_all_ops'] = ops to_commit_sanitized = [] to_commit_reserved = [] ...
<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_block_statistics(cls, block_id): """ Get block statistics. Only works in test mode. """
if not os.environ.get("BLOCKSTACK_TEST"): raise Exception("This method is only available in the test framework") global STATISTICS return STATISTICS.get(block_id)
<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_consensus_at(self, block_id): """ Get the consensus hash at a given block. Return the consensus hash if we have one for this block. Return None if we don...
query = 'SELECT consensus_hash FROM snapshots WHERE block_id = ?;' args = (block_id,) con = self.db_open(self.impl, self.working_dir) rows = self.db_query_execute(con, query, args, verbose=False) res = None for r in rows: res = r['consensus_hash'] ...
<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_block_from_consensus( self, consensus_hash ): """ Get the block number with the given consensus hash. Return None if there is no such block. """
query = 'SELECT block_id FROM snapshots WHERE consensus_hash = ?;' args = (consensus_hash,) con = self.db_open(self.impl, self.working_dir) rows = self.db_query_execute(con, query, args, verbose=False) res = None for r in rows: res = r['block_id'] ...
<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_valid_consensus_hashes( self, block_id ): """ Get the list of valid consensus hashes for a given block. """
first_block_to_check = block_id - self.impl.get_valid_transaction_window() query = 'SELECT consensus_hash FROM snapshots WHERE block_id >= ? AND block_id <= ?;' args = (first_block_to_check,block_id) valid_consensus_hashes = [] con = self.db_open(self.impl, self.worki...
<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(version='bayestar2017'): """ Downloads the specified version of the Bayestar dust map. Args: version (Optional[:obj:`str`]): The map version to downlo...
doi = { 'bayestar2015': '10.7910/DVN/40C44C', 'bayestar2017': '10.7910/DVN/LCYHJG' } # Raise an error if the specified version of the map does not exist try: doi = doi[version] except KeyError as err: raise ValueError('Version "{}" does not exist. Valid versions ar...
<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_jinja2_silent_none(config): # pragma: no cover """ if variable is None print '' instead of 'None' """
config.commit() jinja2_env = config.get_jinja2_environment() jinja2_env.finalize = _silent_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 complex_validates(validate_rule): """Quickly setup attributes validation by one-time, based on `sqlalchemy.orm.validates`. Don't like `sqlalchemy.orm.validat...
ref_dict = { # column_name: ( # (predicate, arg1, ... argN), # ... # ) } for column_names, predicate_refs in validate_rule.items(): for column_name in _to_tuple(column_names): ref_dict[column_name] = \ ref_dict.get(column_name, tuple...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_handler(column_name, value, predicate_refs): """handle predicate's return value"""
# only does validate when attribute value is not None # else, just return it, let sqlalchemy decide if the value was legal according to `nullable` argument's value if value is not None: for predicate_ref in predicate_refs: predicate, predicate_name, predicate_args = _decode_predicate_r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def simple_predictive_probability_multistate(M_c, X_L_list, X_D_list, Y, Q): """Returns the simple predictive probability, averaged over each sample."""
logprobs = [float(simple_predictive_probability(M_c, X_L, X_D, Y, Q)) for X_L, X_D in zip(X_L_list, X_D_list)] return logmeanexp(logprobs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predictive_probability_multistate(M_c, X_L_list, X_D_list, Y, Q): """ Returns the predictive probability, averaged over each sample. """
logprobs = [float(predictive_probability(M_c, X_L, X_D, Y, Q)) for X_L, X_D in zip(X_L_list, X_D_list)] return logmeanexp(logprobs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def similarity( M_c, X_L_list, X_D_list, given_row_id, target_row_id, target_column=None): """Returns the similarity of the given row to the target row, averaged...
score = 0.0 # Set col_idxs: defaults to all columns. if target_column: if type(target_column) == str: col_idxs = [M_c['name_to_idx'][target_column]] elif type(target_column) == list: col_idxs = target_column else: col_idxs = [target_column] 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 admin_docker_list_view(context, request): """Show list of docker images."""
return { 'paginator': Page( context.all, url_maker=lambda p: request.path_url + "?page=%s" % p, page=int(request.params.get('page', 1)), items_per_page=6 ) }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def admin_docker_massaction_view(context, request): """Mass action view."""
items_list = request.POST.getall('selected_item') for item in items_list: try: context.cli.remove_image(item) request.session.flash(["deleted {}".format(item), "success"]) except docker.errors.APIError as e: request.session.flash([e.explanation, "error"]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coord2healpix(coords, frame, nside, nest=True): """ Calculate HEALPix indices from an astropy SkyCoord. Assume the HEALPix system is defined on the coordinat...
if coords.frame.name != frame: c = coords.transform_to(frame) else: c = coords if hasattr(c, 'ra'): phi = c.ra.rad theta = 0.5*np.pi - c.dec.rad return hp.pixelfunc.ang2pix(nside, theta, phi, nest=nest) elif hasattr(c, 'l'): phi = c.l.rad theta =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_gal(self, l, b, d=None, **kwargs): """ Query using Galactic coordinates. Args: l (:obj:`float`, scalar or array-like): Galactic longitude, in degrees,...
if not isinstance(l, units.Quantity): l = l * units.deg if not isinstance(b, units.Quantity): b = b * units.deg if d is None: coords = coordinates.SkyCoord(l, b, frame='galactic') else: if not isinstance(d, units.Quantity): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_request_parser(model_or_inst, excludes=None, only=None, for_populate=False): """Pass a `model class` or `model instance` to this function, then, it will...
is_inst = _is_inst(model_or_inst) if isinstance(excludes, six.string_types): excludes = [excludes] if excludes and only: only = None elif isinstance(only, six.string_types): only = [only] parser = RequestPopulator() if for_populate else reqparse.RequestParser() for col...
<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_flagstate(flagset): """ Set all flags in ``flagset``, and clear all other flags. """
if not flagset <= _all_flags: raise ValueError("unrecognized flags in flagset") for f in flagset: set_flag(f) for f in _all_flags - flagset: clear_flag(f)
<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_str2(s, base, context=None): """ Convert the string ``s`` in base ``base`` to a BigFloat instance, rounding according to the current context. Raise Value...
return _apply_function_in_current_context( BigFloat, _set_from_whole_string, (s, base), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pos(x, context=None): """ Return ``x``. As usual, the result is rounded to the current context. The ``pos`` function can be useful for rounding an intermedia...
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_set, (BigFloat._implicit_convert(x),), context, )
<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(x, y, context=None): """ Return ``x`` + ``y``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_add, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub(x, y, context=None): """ Return ``x`` - ``y``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sub, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mul(x, y, context=None): """ Return ``x`` times ``y``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_mul, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sqr(x, context=None): """ Return the square of ``x``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_sqr, (BigFloat._implicit_convert(x),), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def div(x, y, context=None): """ Return ``x`` divided by ``y``. """
return _apply_function_in_current_context( BigFloat, mpfr.mpfr_div, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def floordiv(x, y, context=None): """ Return the floor of ``x`` divided by ``y``. The result is a ``BigFloat`` instance, rounded to the context if necessary. Spe...
return _apply_function_in_current_context( BigFloat, mpfr_floordiv, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mod(x, y, context=None): """ Return the remainder of x divided by y, with sign matching that of y. """
return _apply_function_in_current_context( BigFloat, mpfr_mod, ( BigFloat._implicit_convert(x), BigFloat._implicit_convert(y), ), context, )