output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Returns the contents of the sql file from the given filename.
Here you have a function in Python 3, explain what it does def _get_sql(filename): with open(os.path.join(SQL_DIR, filename), 'r') as f: return f.read()
You are a Python code analyst, evaluating scripts for potential improvements.
def verify_id_n_version(id, version): """Given an ``id`` and ``version``, verify the identified content exists. """ stmt = _get_sql('verify-id-and-version.sql') args = dict(id=id, version=version) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stm...
Write a Python 3 script to verify that the identified content exists in the database.
You are a Python code generator, capable of creating scripts from specifications.
Return the database type for the given identifier.
Explain what the following Python 3 code does def get_type(ident_hash): id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-type.sql') args = dict(id=id, version=version) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stmt, args) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_metadata(ident_hash): """Return the dictionary of metadata from the database. This data is keyed using the cnx-epub data structure. """ id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-metadata.sql') args = dict(id=id, version=version) # FIXME The license_url and li...
Write a Python 3 script for returning the dictionary of metadata for a given entity.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the content for the given ident_hash.
Make a summary of the following Python 3 code def get_content(ident_hash, context=None): id, version = get_id_n_version(ident_hash) filename = 'index.cnxml.html' if context is not None: stmt = _get_sql('get-baked-content.sql') args = dict(id=id, version=version, context=context) else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_file_info(hash, context=None): """Returns information about the file, identified by ``hash``. If the `context` (an ident-hash) is supplied, the information returned will be specific to that context. """ if context is None: stmt = _get_sql('get-file-info.sql') args = dict(has...
Implement a Python 3 function for returning information about the file identified by hash.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the contents of the file as a memoryview.
Can you tell what is the following Python 3 function doing def get_file(hash): stmt = _get_sql('get-file.sql') args = dict(hash=hash) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stmt, args) try: file, _ = cursor.fetchone() ...
You are a Python code generator, capable of creating scripts from specifications.
def get_registered_files(ident_hash): """Returns a list SHA1 hashes for registered file entries identified by the given module ``ident_hash``. Note, it's possible for a module to reference a file without having a registered file entry for it. Note, all files are included, including the raw form of...
Implement a Python 3 function for returning a list of SHA1 hashes for registered file entries identified by the given module ident_hash.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_tree(ident_hash, baked=False): """Return a tree structure of the Collection""" id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-tree.sql') args = dict(id=id, version=version, baked=baked) with db_connect() as db_conn: with db_conn.cursor() as cursor: curs...
How would you implement a function in Python 3 that returns a tree structure of the Collection
You are a Python code generator, capable of creating scripts from specifications.
Returns the media - type of the file at the given filepath
Explain what the following Python 3 code does def guess_media_type(filepath): o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath]) o = o.strip() return o
As a python code expert, you are capable of creating scripts from specifications.
Look up the module_ident for the given id & version.
Make a summary of the following Python 3 code def lookup_module_ident(id, version): with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute( "SELECT module_ident FROM modules " "WHERE uuid = %s " "AND CONCAT_WS('.', major_vers...
You are a Python code generator, capable of creating scripts from specifications.
Upsert the file and media_type into the files table. Returns the fileid and sha1 of the upserted file.
How would you explain what the following Python 3 function does def insert_file(file, media_type): resource_hash = get_file_sha1(file) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("SELECT fileid FROM files WHERE sha1 = %s", (resourc...
As a Python code translator, you convert algorithms and pseudocode into Python.
Upsert a file associated with fileid with filename as a module_files entry associated with module_ident.
Here you have a function in Python 3, explain what it does def upsert_module_file(module_ident, fileid, filename): with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("SELECT true FROM module_files " "WHERE module_ident = %s " ...
You are a Python code analyst, evaluating scripts for potential improvements.
def inject_resource(ident_hash, file, filename, media_type): """Injects the contents of ``file`` (a file-like object) into the database as ``filename`` with ``media_type`` in association with the content at ``ident_hash``. """ resource_hash = get_file_sha1(file) with db_connect() as db_conn: ...
How would you code a function in Python 3 to inject the contents of file into the database as filename with media_type in association with the content at ident_hash.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_contour(mask): """Compute the image contour from a mask The contour is computed in a very inefficient way using scikit-image and a conversion of float coordinates to pixel coordinates. Parameters ---------- mask: binary ndarray of shape (M,N) or (K,M,N) The mask outlining the p...
Can you implement a function in Python 3 that computes the image contour from a binary array of pixels.
As a Python code analyst, you investigate and solve complex coding mysteries
def scan(self, stop_on_first=True, base_ip=0): """Scans the local network for TVs.""" tvs = [] # Check if base_ip has been passed if base_ip == 0: # Find IP address of computer pymitv is running on sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ...
Implement a Python 3 function for scanning the local network for TVs.
You are a Python code generator, capable of creating scripts from specifications.
Attempts a connection to the TV and checks if there really is a TV.
Here you have a function in Python 3, explain what it does def check_ip(ip, log=False): if log: print('Checking ip: {}...'.format(ip)) request_timeout = 0.1 try: tv_url = 'http://{}:6095/request?action=isalive'.format(ip) request = requests.get(tv_ur...
You are a Python code architect, reviewing and designing scalable and efficient code
Obtain the type name of a GRPC Message field.
Can you generate the documentation for the following Python 3 function def get_field_type(f): types = (t[5:] for t in dir(f) if t[:4] == 'TYPE' and getattr(f, t) == f.type) return next(types)
As a Python code analyst, you investigate and solve complex coding mysteries
def get_field_description(f): """Get the type description of a GRPC Message field.""" type_name = get_field_type(f) if type_name == 'MESSAGE' and \ {sf.name for sf in f.message_type.fields} == {'key', 'value'}: return 'map<string, string>' elif type_name == 'MESSAGE': return ...
Implement a function in Python 3 to get the type description of a GRPC Message field.
You are a Python code generator, capable of creating scripts from specifications.
Creates a request from a static method function call.
Can you tell what is the following Python 3 function doing def make_static_request(method, *args, **kwargs): if args and not use_signature: raise NotImplementedError("Only keyword arguments allowed in Python2") if use_signature: new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()} ...
As a Python code analyst, you investigate and solve complex coding mysteries
Creates a request from a method function call.
Can you generate the documentation for the following Python 3 function def make_request(self, method, *args, **kwargs): if args and not use_signature: raise NotImplementedError("Only keyword arguments allowed in Python2") new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()} if use_sign...
As a Python code analyst, you investigate and solve complex coding mysteries
Generates a method from a GrpcMethod definition.
Can you generate the documentation for the following Python 3 function def method_wrapper(m): if m.is_simple: def simple_method(self): """TODO: no docstring!""" return apply_transform( self.__service__, m.output_transform, grpc_call(self.__service__, ...
As a Python code analyst, you investigate and solve complex coding mysteries
Generate the name of the request.
Explain what the following Python 3 code does def request_name(self): if self.static and not self.uses_request: return 'Empty' if not self.uses_request: return None if isinstance(self.uses_request, str): return self.uses_request return to_camel_case...
You are a Python code generator, capable of creating scripts from specifications.
def request_type(self): """Retrieve the type of the request, by fetching it from `xenon.proto.xenon_pb2`.""" if self.static and not self.uses_request: return getattr(xenon_pb2, 'Empty') if not self.uses_request: return None return getattr(xenon_pb2, self...
Create a Python 3 function for retrieving the type of the request from the XMPP protocol.
As a Python code composer, you craft elegant and concise scripts.
def signature(self): """Create a signature for this method, only in Python > 3.4""" if not use_signature: raise NotImplementedError("Python 3 only.") if self.static: parameters = \ (Parameter(name='cls', kind=Parameter.POSITIONA...
How would you implement a function in Python 3 that creates a signature for this method only in Python > 3. 4.
You are a Python code architect, reviewing and designing scalable and efficient code
Generate a doc - string.
Explain what the following Python 3 code does def docstring(self, servicer): s = getattr(servicer, to_lower_camel_case(self.name)).__doc__ \ or "TODO: no docstring in .proto file" if self.uses_request: s += "\n" for field in get_fields(self.request_type): ...
You are a Python code generator, capable of creating scripts from specifications.
def slugify(string): """Return a slug for the unicode_string. (lowercase, only letters and numbers, hyphens replace spaces) """ filtered_string = [] if isinstance(string, str): string = unicode(string, 'utf-8') for i in unicodedata.normalize('NFKC', string): cat = unicodedata.ca...
Can you write a function in Python 3 where it returns a slug for the unicode_string.
As a python code expert, you are capable of creating scripts from specifications.
def utf8(item): """Change all python2 str/bytes instances to unicode/python3 str.""" if isinstance(item, list): return [utf8(i) for i in item] if isinstance(item, tuple): return tuple([utf8(i) for i in item]) if isinstance(item, dict): return {utf8(k): utf8(v) for k, v in item.it...
Can you write a function in Python 3 where it changes all python2 str instances to unicode / python3 str.
You are a Python code analyst, evaluating scripts for potential improvements.
Update the filters according to self. rtdc_ds. config. filtering.
Given the following Python 3 function, write the documentation def update(self, force=[]): # These lists may help us become very fast in the future newkeys = [] oldvals = [] newvals = [] cfg_cur = self.rtdc_ds.config["filtering"] cfg_old = self._old_config # De...
You are a Python code generator, capable of creating scripts from specifications.
def find_contours(array, level, fully_connected='low', positive_orientation='low'): """Find iso-valued contours in a 2D array for a given level value. Uses the "marching squares" method to compute a the iso-valued contours of the input 2D array for a particular level value. Array values a...
Can you implement a function in Python 3 that finds iso-valued contours in a 2D array for a given level value. Uses the "marching squares" method to compute a the iso-valued contours of the input 2D array for a particular level value. Array values are linearly interpolated to provide better precision for the output con...
As a python code expert, you are capable of creating scripts from specifications.
Return the moduleid for a given ident_hash.
Can you generate a brief explanation for the following Python 3 code def get_module_ident_from_ident_hash(ident_hash, cursor): try: uuid, (mj_ver, mn_ver) = split_ident_hash( ident_hash, split_version=True) except IdentHashMissingVersion as e: uuid, mj_ver, mn_ver = e.id, None, None ...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_tree(ident_hash, cursor, as_collated=False): """Return a JSON representation of the binder tree for ``ident_hash``.""" uuid, version = split_ident_hash(ident_hash) cursor.execute(SQL['get-tree-by-uuid-n-version'], (uuid, version, as_collated,)) try: tree = cursor.fetch...
Can you implement a function in Python 3 that returns a JSON representation of the binder tree for ident_hash.
As a python code expert, you are capable of creating scripts from specifications.
def get_collated_content(ident_hash, context_ident_hash, cursor): """Return collated content for ``ident_hash``.""" cursor.execute(SQL['get-collated-content'], (ident_hash, context_ident_hash,)) try: return cursor.fetchone()[0] except TypeError: # NoneType return
Implement a function in Python 3 to return collated content for ident_hash.
As a Python code composer, you craft elegant and concise scripts.
def get_module_uuid(plpy, moduleid): """Retrieve page uuid from legacy moduleid.""" plan = plpy.prepare("SELECT uuid FROM modules WHERE moduleid = $1;", ('text',)) result = plpy.execute(plan, (moduleid,), 1) if result: return result[0]['uuid']
Write a Python 3 script to retrieve page uuid from legacy moduleid.
You are a Python code analyst, evaluating scripts for potential improvements.
Retrieve the module_ident for a given moduleid.
Here you have a function in Python 3, explain what it does def get_current_module_ident(moduleid, plpy): plan = plpy.prepare('''\ SELECT m.module_ident FROM modules m WHERE m.moduleid = $1 ORDER BY revised DESC''', ('text',)) results = plpy.execute(plan, (moduleid,), 1) if results: r...
You are a Python code architect, reviewing and designing scalable and efficient code
Retrieve minor version only given module_ident.
Here you have a function in Python 3, explain what it does def get_minor_version(module_ident, plpy): # Make sure to always return the max minor version that is already in the # database, in case the given module_ident is not the latest version plan = plpy.prepare('''\ WITH t AS ( SELECT...
As a Python code composer, you craft elegant and concise scripts.
def get_collections(module_ident, plpy): """Get all the collections that the module is part of.""" # Make sure to only return one match per collection and only if it is the # latest collection (which may not be the same as what is in # latest_modules) plan = plpy.prepare(''' WITH RECURSIVE t(node, p...
Implement a function in Python 3 to get all the collections that the module is part of.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_subcols(module_ident, plpy): """Get all the sub-collections that the module is part of.""" plan = plpy.prepare(''' WITH RECURSIVE t(node, parent, path, document) AS ( SELECT tr.nodeid, tr.parent_id, ARRAY[tr.nodeid], tr.documentid FROM trees tr WHERE tr.documentid = $1 and tr...
Create a Python 3 function for getting all the sub - collections that the module is part of.
You are a Python code architect, reviewing and designing scalable and efficient code
def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy): """Create a new tree for the collection based on the old tree. This uses new document ids, replacing old ones. """ get_tree = plpy.prepare(''' WITH RECURSIVE t(node, parent, document, title, childorder, latest, path) ...
Write a Python 3 function that can rebuild the tree based on the old collection.
As a Python code composer, you craft elegant and concise scripts.
def republish_collection(submitter, submitlog, next_minor_version, collection_ident, plpy, revised=None): """Insert a new row for collection_ident with a new version. Returns the module_ident of the row inserted. """ sql = ''' INSERT INTO modules (portal_type, moduleid, uui...
How would you code a function in Python 3 to republish a new version of the modules in the specified collection.
As a python code expert, you are capable of creating scripts from specifications.
def set_version(portal_type, legacy_version, td): """Set the major_version and minor_version if they are not set.""" modified = 'OK' legacy_major, legacy_minor = legacy_version.split('.') if portal_type == 'Collection': # For collections, both major and minor needs to be set modified = ...
Can you create a Python 3 function that sets the major_version and minor_version of the current object.
As a python code expert, you are capable of creating scripts from specifications.
This function is used to republish a module. It will create a new minor version of collections.
Make a summary of the following Python 3 code def republish_module(td, plpy): portal_type = td['new']['portal_type'] modified = 'OK' moduleid = td['new']['moduleid'] legacy_version = td['new']['version'] submitter = td['new']['submitter'] submitlog = td['new']['submitlog'] modified = set_ve...
You are a Python code generator, capable of creating scripts from specifications.
def republish_module_trigger(plpy, td): """Trigger called from postgres database when republishing a module. When a module is republished, the versions of the collections that it is part of will need to be updated (a minor update). e.g. there is a collection c1 v2.1, which contains module m1 v3 ...
How would you code a function in Python 3 to trigger called from postgres database when republishing a module.
You are a Python code generator, capable of creating scripts from specifications.
Trigger to fill in legacy moduleid when publishing.
Explain what the following Python 3 code does def assign_moduleid_default_trigger(plpy, td): modified_state = "OK" portal_type = td['new']['portal_type'] uuid = td['new']['uuid'] moduleid = td['new']['moduleid'] version = td['new']['version'] # Is this an insert from legacy? Legacy always suppl...
As a Python code analyst, you investigate and solve complex coding mysteries
def assign_version_default_trigger(plpy, td): """Trigger to fill in legacy data fields. A compatibilty trigger to fill in legacy data fields that are not populated when inserting publications from cnx-publishing. If this is not a legacy publication the ``version`` will be set based on the ``major_...
Can you implement a function in Python 3 that assigns the default version to the noton version field.
You are a Python code analyst, evaluating scripts for potential improvements.
def assign_document_controls_default_trigger(plpy, td): """Trigger to fill in document_controls when legacy publishes. A compatibilty trigger to fill in ``uuid`` and ``licenseid`` columns of the ``document_controls`` table that are not populated when inserting publications from legacy. This uuid d...
Create a Python 3 function to assign default document_controls to the noton_document_controls table.
As a Python code composer, you craft elegant and concise scripts.
Trigger for filling in acls when legacy publishes.
Can you generate the documentation for the following Python 3 function def upsert_document_acl_trigger(plpy, td): modified_state = "OK" uuid_ = td['new']['uuid'] authors = td['new']['authors'] and td['new']['authors'] or [] maintainers = td['new']['maintainers'] and td['new']['maintainers'] or [] is...
As a Python code analyst, you investigate and solve complex coding mysteries
A compatibility trigger to upsert users from legacy persons table.
Can you generate a brief explanation for the following Python 3 code def upsert_users_from_legacy_publication_trigger(plpy, td): modified_state = "OK" authors = td['new']['authors'] and td['new']['authors'] or [] maintainers = td['new']['maintainers'] and td['new']['maintainers'] or [] licensors = td['n...
You are a Python code architect, reviewing and designing scalable and efficient code
Trigger to insert users from moduleoptionalroles.
Make a summary of the following Python 3 code def insert_users_for_optional_roles_trigger(plpy, td): modified_state = "OK" users = td['new']['personids'] and td['new']['personids'] or [] plan = plpy.prepare("""\ SELECT username FROM users WHERE username = any($1)""", ['text[]']) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def add_module_file(plpy, td): """Database trigger for adding a module file. When a legacy ``index.cnxml`` is added, this trigger transforms it into html and stores it as ``index.cnxml.html``. When a cnx-publishing ``index.cnxml.html`` is added, this trigger checks if ``index.html.cnxml`` exists be...
Implement a Python 3 function for adding a module file to the internal list of modules.
You are a Python code generator, capable of creating scripts from specifications.
def _transform_abstract(plpy, module_ident): """Transform abstract, bi-directionally. Transforms an abstract using one of content columns ('abstract' or 'html') to determine which direction the transform will go (cnxml->html or html->cnxml). A transform is done on either one of them to make the...
Write a Python 3 script for transforming an abstract using bi - directionally.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_collection_tree(collection_ident, cursor): """Build and retrieve json tree representation of a book.""" cursor.execute(''' WITH RECURSIVE t(node, parent, document, path) AS ( SELECT tr.nodeid, tr.parent_id, tr.documentid, ARRAY[tr.nodeid] FROM trees tr WHERE tr.documentid = %...
Write a Python 3 function that can build and retrieve json tree representation of a book.
As a python code expert, you are capable of creating scripts from specifications.
Return userids allowed to publish this book.
Can you generate the documentation for the following Python 3 function def get_module_can_publish(cursor, id): cursor.execute(""" SELECT DISTINCT user_id FROM document_acl WHERE uuid = %s AND permission = 'publish'""", (id,)) return [i[0] for i in cursor.fetchall()]
As a python code expert, you are capable of creating scripts from specifications.
Assembles tree nodes into object models.
Explain what the following Python 3 code does def tree_to_nodes(tree, context=None, metadata=None): nodes = [] for item in tree['contents']: if 'contents' in item: sub_nodes = tree_to_nodes(item, context=context, metadata=metadata) if metadata is None: metadata = ...
As a Python code composer, you craft elegant and concise scripts.
Creates an epub from an ident_hash which is output to the given file - like object. Returns None writes to the given file.
How would you explain what the following Python 3 function does def create_epub(ident_hash, file, format='raw'): model = factory(ident_hash, baked=(format != 'raw')) if isinstance(model, cnxepub.Document): model = cnxepub.TranslucentBinder(nodes=[model]) cnxepub.make_epub(model, file)
You are a Python code analyst, evaluating scripts for potential improvements.
Retrieve an export file.
Make a summary of the following Python 3 code def get_export(request): settings = get_current_registry().settings exports_dirs = settings['exports-directories'].split() args = request.matchdict ident_hash, type = args['ident_hash'], args['type'] id, version = split_ident_hash(ident_hash) with d...
You are a Python code generator, capable of creating scripts from specifications.
Retrieve files associated with document.
Can you generate the documentation for the following Python 3 function def get_export_files(cursor, id, version, types, exports_dirs, read_file=True): request = get_current_request() type_info = dict(request.registry.settings['_type_info']) metadata = get_content_metadata(id, version, cursor) legacy_id ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_content_metadata(id, version, cursor): """Return metadata related to the content from the database.""" # Do the module lookup args = dict(id=id, version=version) # FIXME We are doing two queries here that can hopefully be # condensed into one. cursor.execute(SQL['get-module-metadat...
Create a Python 3 function to return metadata related to the content from the database.
You are a Python code generator, capable of creating scripts from specifications.
Find contours for a given level value in a given density estimate.
Can you generate the documentation for the following Python 3 function def find_contours_level(density, x, y, level, closed=False): if level >= 1 or level <= 0: raise ValueError("`level` must be in (0,1), got '{}'!".format(level)) # level relative to maximum level = level * density.max() # xy co...
You are a Python code analyst, evaluating scripts for potential improvements.
def _find_quantile_level(density, x, y, xp, yp, quantile, acc=.01, ret_err=False): """Find density level for a given data quantile by iteration Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ...
Write a Python 3 script for finding the density level for a given data quantile by iteration.
As a Python code translator, you convert algorithms and pseudocode into Python.
Writes data to an RT - DC file.
Can you generate the documentation for the following Python 3 function def write(path_or_h5file, data={}, meta={}, logs={}, mode="reset", compression=None): """Write data to an RT-DC file Parameters ---------- path: path or h5py.File The path or the hdf5 file object to write to. d...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _convert(tup, dictlist): """ :param tup: a list of tuples :param di: a dictionary converted from tup :return: dictionary """ di = {} for a, b in tup: di.setdefault(a, []).append(b) for key, val in di.items(): dictlist.append((key, val)) return dictlist
How would you code a function in Python 3 to convert a tuple into a list of tuples.
As a Python code analyst, you investigate and solve complex coding mysteries
def _upper(val_list): """ :param val_list: a list of strings :return: a list of upper-cased strings """ res = [] for ele in val_list: res.append(ele.upper()) return res
Implement a function in Python 3 to return a list of upper - cased strings
As a Python code analyst, you investigate and solve complex coding mysteries
Construct the search statment for the DBAPI v2 execute method.
Make a summary of the following Python 3 code def _build_search(structured_query): arguments = {} # get text terms and filter out common words text_terms = [term for ttype, term in structured_query.terms if ttype == 'text'] text_terms_wo_stopwords = [term for term in text_terms ...
You are a Python code analyst, evaluating scripts for potential improvements.
def search(query, query_type=DEFAULT_QUERY_TYPE): """Search database using parsed query. Executes a database search query from the given ``query`` (a ``Query`` object) and optionally accepts a list of search weights. By default, the search results are ordered by weight. :param query: containing te...
Implement a Python 3 function for searching database using parsed query.
As a python code expert, you are capable of creating scripts from specifications.
def from_raw_query(cls, query_string): """Parse raw string to query. Given a raw string (typically typed by the user), parse to a structured format and initialize the class. """ try: node_tree = grammar.parse(query_string) except IncompleteParseError: ...
Implement a function in Python 3 to parse a raw string to query. Given a raw string to query. Parse to a structured format and initialize the class.
As a Python code analyst, you investigate and solve complex coding mysteries
Highlight the found terms in the abstract text.
Explain what the following Python 3 code does def highlighted_abstract(self): abstract_terms = self.fields.get('abstract', []) if abstract_terms: sql = _read_sql_file('highlighted-abstract') else: sql = _read_sql_file('get-abstract') arguments = {'id': self['id'],...
As a Python code analyst, you investigate and solve complex coding mysteries
def highlighted_fulltext(self): """Highlight the found terms in the fulltext.""" terms = self.fields.get('fulltext', []) if not terms: return None arguments = {'id': self['id'], 'query': ' & '.join(terms), } with db_connect() ...
Can you implement a function in Python 3 that highlights the found terms in the fulltext field.
You are a Python code architect, reviewing and designing scalable and efficient code
r Evaluate the probability density function at data_predict.
Can you generate a brief explanation for the following Python 3 code def pdf(self, data_predict=None): if data_predict is None: data_predict = self.data else: data_predict = _adjust_shape(data_predict, self.k_vars) pdf_est = [] for i in range(np.shape(data_predic...
As a Python code composer, you craft elegant and concise scripts.
def find_xenon_grpc_jar(): """Find the Xenon-GRPC jar-file, windows version.""" prefix = Path(sys.prefix) locations = [ prefix / 'lib', prefix / 'local' / 'lib' ] for location in locations: jar_file = location / 'xenon-grpc-{}-all.jar'.format( xenon_grpc_ver...
Implement a function in Python 3 to find the Xenon - GRPC jar - file windows version.
You are a Python code analyst, evaluating scripts for potential improvements.
Kill the process group associated with the given process.
How would you explain what the following Python 3 function does def kill_process(process): logger = logging.getLogger('xenon') logger.info('Terminating Xenon-GRPC server.') os.kill(process.pid, signal.SIGINT) process.wait()
As a Python code composer, you craft elegant and concise scripts.
Start the xenon - grpc server.
Can you generate the documentation for the following Python 3 function def start_xenon_server(port=50051, disable_tls=False): jar_file = find_xenon_grpc_jar() if not jar_file: raise RuntimeError("Could not find 'xenon-grpc' jar file.") cmd = ['java', '-jar', jar_file, '-p', str(port)] if not d...
As a Python code analyst, you investigate and solve complex coding mysteries
Connects to TV and sends keystrokes via HTTP.
Given the following Python 3 function, write the documentation def send_keystrokes(ip, keystrokes, wait=False): tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip) for keystroke in keystrokes: if keystroke == 'wait' or wait is True: time.sleep(0.7...
You are a Python code analyst, evaluating scripts for potential improvements.
Full text in - book search.
Can you generate the documentation for the following Python 3 function def in_book_search(request): results = {} args = request.matchdict ident_hash = args['ident_hash'] args['search_term'] = request.params.get('q', '') query_type = request.params.get('query_type', '') combiner = '' if que...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _adjust_shape(dat, k_vars): """ Returns an array of shape (nobs, k_vars) for use with `gpke`.""" dat = np.asarray(dat) if dat.ndim > 2: dat = np.squeeze(dat) if dat.ndim == 1 and k_vars > 1: # one obs many vars nobs = 1 elif dat.ndim == 1 and k_vars == 1: # one obs one var ...
How would you code a function in Python 3 to return an array of shape nobs k_vars for use with GPG.
As a Python code analyst, you investigate and solve complex coding mysteries
r Returns the non - normalized Generalized Product Kernel Estimator for the pdf.
Given the following Python 3 function, write the documentation def gpke(bw, data, data_predict, var_type, ckertype='gaussian', okertype='wangryzin', ukertype='aitchisonaitken', tosum=True): r""" Returns the non-normalized Generalized Product Kernel Estimator Parameters ---------- bw: 1-D n...
You are a Python code architect, reviewing and designing scalable and efficient code
def _compute_bw(self, bw): """ Computes the bandwidth of the data. Parameters ---------- bw: array_like or str If array_like: user-specified bandwidth. If a string, should be one of: - cv_ml: cross validation maximum likelihood ...
Write a Python 3 script for computing the bandwidth of the data.
As a Python code translator, you convert algorithms and pseudocode into Python.
Sets the default values for the efficient estimation
Can you generate the documentation for the following Python 3 function def _set_defaults(self, defaults): self.n_res = defaults.n_res self.n_sub = defaults.n_sub self.randomize = defaults.randomize self.return_median = defaults.return_median self.efficient = defaults.efficient ...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_version(): """Return package version from setup.cfg""" config = RawConfigParser() config.read(os.path.join('..', 'setup.cfg')) return config.get('metadata', 'version')
Can you write a function in Python 3 where it returns package version from setup. cfg
You are a Python code generator, capable of creating scripts from specifications.
Convert SitemapIndex into a string.
Can you tell what is the following Python 3 function doing def to_string(self): root = etree.Element('sitemapindex', nsmap={None: SITEMAP_NS}) for sitemap in self.sitemaps: sm = etree.SubElement(root, 'sitemap') etree.SubElement(sm, 'loc').text = sitemap.url if hasatt...
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a new url to the sitemap.
Explain what the following Python 3 code does def add_url(self, *args, **kwargs): if len(args) == 1 and not kwargs and isinstance(args[0], UrlEntry): self.urls.append(args[0]) else: self.urls.append(UrlEntry(*args, **kwargs))
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert the sitemap into a string.
Make a summary of the following Python 3 code def to_string(self): root = etree.Element('urlset', nsmap={None: SITEMAP_NS}) for url in self.urls: url.generate(root) return etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='utf-8')
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate the url element under root_element.
How would you explain what the following Python 3 function does def generate(self, root_element=None): if root_element is not None: url = etree.SubElement(root_element, 'url') else: url = etree.Element('url') etree.SubElement(url, 'loc').text = self.loc if self.la...
You are a Python code analyst, evaluating scripts for potential improvements.
Creates a queue and a co - routine yielding from that .
Make a summary of the following Python 3 code def make_input_stream(): input_queue = Queue() def input_stream(): while True: cmd, msg = input_queue.get() if cmd == 'end': input_queue.task_done() return elif cmd == 'msg': ...
As a Python code analyst, you investigate and solve complex coding mysteries
Determine if given url is a page that should be in sitemap.
How would you explain what the following Python 3 function does def notblocked(page): for blocked in PAGES_TO_BLOCK: if blocked[0] != '*': blocked = '*' + blocked rx = re.compile(blocked.replace('*', '[^$]*')) if rx.match(page): return False return True
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a sitemap xml file for search engines.
Make a summary of the following Python 3 code def sitemap(request): xml = Sitemap() author = request.matchdict.get('from_id') if author is not None: match = "AND '{}' = authors[1]".format(author) else: match = '' with db_connect() as db_connection: with db_connection.cursor(...
As a Python code analyst, you investigate and solve complex coding mysteries
Return a sitemap index xml file for search engines.
Given the following Python 3 function, write the documentation def sitemap_index(request): sitemaps = [] with db_connect() as db_connection: with db_connection.cursor() as cursor: cursor.execute("""\ SELECT authors[1], max(revised) FROM latest_modules ...
As a Python code composer, you craft elegant and concise scripts.
Calculate the volume of a polygon revolved around an axis.
Can you generate the documentation for the following Python 3 function def get_volume(cont, pos_x, pos_y, pix): if np.isscalar(pos_x): cont = [cont] ret_list = False else: ret_list = True # Convert input to 1D arrays pos_x = np.atleast_1d(pos_x) pos_y = np.atleast_1d(pos_y) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Put contour coordinates into counter - clockwise order.
Here you have a function in Python 3, explain what it does def counter_clockwise(cx, cy): # test orientation angles = np.unwrap(np.arctan2(cy, cx)) grad = np.gradient(angles) if np.average(grad) > 0: return cx[::-1], cy[::-1] else: return cx, cy
As a python code expert, you are capable of creating scripts from specifications.
def add_metadata_sectors(self, vtoc, sector_list, header): """Add track/sector list """ tslist = BaseSectorList(header) for start in range(0, len(sector_list), header.ts_pairs): end = min(start + header.ts_pairs, len(sector_list)) if _xd: log.debug("ts: %d-%d" % (...
Write a Python 3 function that can add track and sectors to the metadata.
As a Python code composer, you craft elegant and concise scripts.
def _get_subject_list_generator(cursor): """Return all subjects (tags) in the database except "internal" scheme.""" subject = None last_tagid = None cursor.execute(SQL['get-subject-list']) for s in cursor.fetchall(): tagid, tagname, portal_type, count = s if tagid != last_tagid: ...
Write a Python 3 script for returning all subjects in the database except internal scheme.
You are a Python code architect, reviewing and designing scalable and efficient code
Return a dict with archive metadata for webview.
Here you have a function in Python 3, explain what it does def extras(request): key = request.matchdict.get('key', '').lstrip('/') key_map = { 'languages': _get_available_languages_and_count, 'subjects': _get_subject_list, 'featured': _get_featured_links, 'messages': _get_service...
As a Python code analyst, you investigate and solve complex coding mysteries
def timeout(delay, call, *args, **kwargs): """Run a function call for `delay` seconds, and raise a RuntimeError if the operation didn't complete.""" return_value = None def target(): nonlocal return_value return_value = call(*args, **kwargs) t = Thread(target=target) t.start() ...
Write a Python 3 function that can run a function call for delay seconds and raise a RuntimeError if the operation didn t complete.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create an argument parser with the given name and description.
Make a summary of the following Python 3 code def create_parser(name, description=None): prog = _gen_prog_name(name) parser = argparse.ArgumentParser(prog=prog, description=description) parser.add_argument('config_uri', help="Configuration INI file.") parser.add_argument('--config-name', ...
As a Python code analyst, you investigate and solve complex coding mysteries
Parse the arguments into app settings.
Make a summary of the following Python 3 code def get_app_settings_from_arguments(args): config_filepath = os.path.abspath(args.config_uri) return get_appsettings(config_filepath, name=args.config_name)
You are a Python code architect, reviewing and designing scalable and efficient code
def check_socket(host, port): """Checks if port is open on host. This is used to check if the Xenon-GRPC server is running.""" with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: return sock.connect_ex((host, port)) == 0
Implement a function in Python 3 to check if port is open on host.
You are a Python code analyst, evaluating scripts for potential improvements.
Try to connect over a secure channel.
Can you generate a brief explanation for the following Python 3 code def get_secure_channel(crt_file, key_file, port=50051): creds = grpc.ssl_channel_credentials( root_certificates=open(str(crt_file), 'rb').read(), private_key=open(str(key_file), 'rb').read(), certificate_chain=open(str(crt...
You are a Python code architect, reviewing and designing scalable and efficient code
def find_free_port(): """Finds a free port.""" with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: sock.bind(('', 0)) return sock.getsockname()[1]
Create a Python 3 function for finding a free port.
As a Python code analyst, you investigate and solve complex coding mysteries
def print_stream(file, name): """Print stream from file to logger.""" logger = logging.getLogger('xenon.{}'.format(name)) for line in file: logger.info('[{}] {}'.format(name, line.strip()))
Create a Python 3 function for printing stream from file to logger.
You are a Python code generator, capable of creating scripts from specifications.
def init(port=None, do_not_exit=False, disable_tls=False, log_level='WARNING'): """Start the Xenon GRPC server on the specified port, or, if a service is already running on that port, connect to that. If no port is given, a random port is selected. This means that, by default, every python instance wil...
Implement a function in Python 3 to start the Xenon GRPC server on the specified port.
You are a Python code architect, reviewing and designing scalable and efficient code