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 file_manifest(self, location): """ An iterator through the files in a location which yields item elements suitable for insertion into the package manifest. "...
#Maps file extensions to mimetypes mimetypes = {'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.xml': 'application/xhtml+xml', '.png': 'image/png', '.css': 'text/css', '.ncx': 'application/x-dtbncx+x...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_contrib_names(self, contrib): """ Returns an appropriate Name and File-As-Name for a contrib element. This code was refactored out of nav_contributors an...
collab = contrib.find('collab') anon = contrib.find('anonymous') if collab is not None: proper_name = serialize(collab, strip=True) file_as_name = proper_name elif anon is not None: proper_name = 'Anonymous' file_as_name = proper_name ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def package_description(self): """ Given an Article class instance, this is responsible for returning an article description. For this method I have taken the ap...
abstract = self.article.root.xpath('./front/article-meta/abstract') return serialize(abstract[0], strip=True) if abstract 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 heading_title(self): """ Makes the Article Title for the Heading. Metadata element, content derived from FrontMatter """
art_title = self.article.root.xpath('./front/article-meta/title-group/article-title')[0] article_title = deepcopy(art_title) article_title.tag = 'h1' article_title.attrib['id'] = 'title' article_title.attrib['class'] = 'article-title' return article_title
<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_heading_authors(self, authors): """ Constructs the Authors content for the Heading. This should display directly after the Article Title. Metadata eleme...
author_element = etree.Element('h3', {'class': 'authors'}) #Construct content for the author element first = True for author in authors: if first: first = False else: append_new_text(author_element, ',', join_str='') co...
<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_heading_affiliations(self, heading_div): """ Makes the content for the Author Affiliations, displays after the Authors segment in the Heading. Metadata ...
#Get all of the aff element tuples from the metadata affs = self.article.root.xpath('./front/article-meta/aff') #Create a list of all those pertaining to the authors author_affs = [i for i in affs if 'aff' in i.attrib['id']] #Count them, used for formatting if len(author...
<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_heading_abstracts(self, heading_div): """ An article may contain data for various kinds of abstracts. This method works on those that are included in th...
for abstract in self.article.root.xpath('./front/article-meta/abstract'): #Make a copy of the abstract abstract_copy = deepcopy(abstract) abstract_copy.tag = 'div' #Abstracts are a rather diverse bunch, keep an eye on them! title_text = abstract_copy....
<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_article_info_funding(self, article_info_div): """ Creates the element for declaring Funding in the article info. """
funding_group = self.article.root.xpath('./front/article-meta/funding-group') if funding_group: funding_div = etree.SubElement(article_info_div, 'div', {'id': 'funding'}) funding_b = etree.SubE...
<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_article_info_competing_interests(self, article_info_div): """ Creates the element for declaring competing interests in the article info. """
#Check for author-notes con_expr = "./front/article-meta/author-notes/fn[@fn-type='conflict']" conflict = self.article.root.xpath(con_expr) if not conflict: return conflict_div = etree.SubElement(article_info_div, 'div', ...
<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_article_info_correspondences(self, article_info_div): """ Articles generally provide a first contact, typically an email address for one of the authors....
corresps = self.article.root.xpath('./front/article-meta/author-notes/corresp') if corresps: corresp_div = etree.SubElement(article_info_div, 'div', {'id': 'correspondence'}) for corresp in corresp...
<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_back_glossary(self, body): """ Glossaries are a fairly common item in papers for PLoS, but it also seems that they are rarely incorporated into the PLoS...
for glossary in self.article.root.xpath('./back/glossary'): gloss_copy = deepcopy(glossary) gloss_copy.tag = 'div' gloss_copy.attrib['class'] = 'back-glossary' body.append(gloss_copy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_disp_quote_elements(self): """ Extract or extended quoted passage from another work, usually made typographically distinct from surrounding text <dis...
for disp_quote in self.main.getroot().findall('.//disp-quote'): if disp_quote.getparent().tag == 'p': elevate_element(disp_quote) disp_quote.tag = 'div' disp_quote.attrib['class'] = 'disp-quote'
<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_single_representation(self, item_xlink_href): """ This function will render a formatted URL for accessing the PLoS' server SingleRepresentation of an o...
#A dict of URLs for PLoS subjournals journal_urls = {'pgen': 'http://www.plosgenetics.org/article/{0}', 'pcbi': 'http://www.ploscompbiol.org/article/{0}', 'ppat': 'http://www.plospathogens.org/article/{0}', 'pntd': 'http://www.plos...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_verse_group_elements(self): """ A song, poem, or verse Implementor’s Note: No attempt has been made to retain the look or visual form of the original...
for verse_group in self.main.getroot().findall('.//verse-group'): #Find some possible sub elements for the heading label = verse_group.find('label') title = verse_group.find('title') subtitle = verse_group.find('subtitle') #Modify the verse-group elem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_list_elements(self): """ A sequence of two or more items, which may or may not be ordered. The <list> element has an optional <label> element and opt...
#I have yet to gather many examples of this element, and may have to #write a recursive method for the processing of lists depending on how #PLoS produces their XML, for now this method is ignorant of nesting #TODO: prefix-words, one possible solution would be to have this method ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def absolute_path(user_path): """ Some paths must be made absolute, this will attempt to convert them. """
if os.path.abspath(user_path): return unix_path_coercion(user_path) else: try: openaccess_epub.utils.evaluate_relative_path(relative=user_path) except: raise ValidationError('This path could not be rendered as absolute')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encloses(self, location: FileLocation ) -> Optional[FunctionDesc]: """ Returns the function, if any, that encloses a given location. """
for func in self.in_file(location.filename): if location in func.location: return func return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in_file(self, filename: str) -> Iterator[FunctionDesc]: """ Returns an iterator over all of the functions definitions that are contained within a given file. ...
yield from self.__filename_to_functions.get(filename, [])
<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_config(args): """ Try to load config, to load other journal locations Otherwise, return default location Returns journal location """
# Try user config or return default location early config_path = path.expanduser(args.config_file) if not path.exists(config_path): # Complain if they provided non-existant config if args.config_file != DEFAULT_JOURNAL_RC: print("journal: error: config file '" + args.config_file...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def record_entries(journal_location, entries): """ args entry - list of entries to record """
check_journal_dest(journal_location) current_date = datetime.datetime.today() date_header = current_date.strftime("%a %H:%M:%S %Y-%m-%d") + "\n" with open(build_journal_path(journal_location, current_date), "a") as date_file: entry_output = date_header # old style # for entry in...
<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_entry(journal_location, date): """ args date - date object returns entry text or None if entry doesn't exist """
if not isinstance(date, datetime.date): return None try: with open(build_journal_path(journal_location, date), "r") as entry_file: return entry_file.read() except IOError: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace( fname1, fname2, dfilter1, dfilter2, has_header1=True, has_header2=True, frow1=0, frow2=0, ofname=None, ocols=None, ): r""" Replace data in one file ...
# pylint: disable=R0913,R0914 irmm_ex = pexdoc.exh.addex( RuntimeError, "Number of input and replacement columns are different" ) iomm_ex = pexdoc.exh.addex( RuntimeError, "Number of input and output columns are different" ) # Read and validate input data iobj = CsvFile(fnam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spmt(t, peak_delay=6, under_delay=16, peak_disp=1, under_disp=1, p_u_ratio=6): """Normalized SPM HRF function from sum of two gamma PDFs Parameters t : array...
return spm_hrf_compat(t, peak_delay=peak_delay, under_delay=under_delay, peak_disp=peak_disp, under_disp=under_disp, p_u_ratio=p_u_ratio, normalize=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 ddspmt(t, peak_delay=6, under_delay=16, peak_disp=1, under_disp=1, p_u_ratio=6): """ SPM canonical HRF dispersion derivative, values for time values `t` Para...
_spm_dd_func = partial(spmt, peak_delay=peak_delay, under_delay=under_delay, under_disp=under_disp, p_u_ratio=p_u_ratio, peak_disp=1.01) return (spmt(t) - _spm_dd_func(t)) / 0.01
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_boxcar(aryCnd, aryOns, aryDrt, varTr, varNumVol, aryExclCnd=None, varTmpOvsmpl=1000.): """ Creation of condition time courses in temporally upsampled ...
if aryExclCnd is not None: for cond in aryExclCnd: aryOns = aryOns[aryCnd != cond] aryDrt = aryDrt[aryCnd != cond] aryCnd = aryCnd[aryCnd != cond] resolution = varTr / float(varTmpOvsmpl) aryCnd = np.asarray(aryCnd) aryOns = np.asarray(aryOns, dtype=np.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 create_inputs_to_reference(job_data, input_files, input_directories): """ Creates a dictionary with the summarized information in job_data, input_files and i...
return {**deepcopy(job_data), **deepcopy(input_files), **deepcopy(input_directories)}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def split_all(reference, sep): """ Splits a given string at a given separator or list of separators. :param reference: The reference to split. :param sep: Separa...
parts = partition_all(reference, sep) return [p for p in parts if p not in sep]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_file(attributes, input_file, input_identifier, input_reference): """ Returns the attributes in demand of the input file. :param attributes: A list o...
if input_file['isArray']: raise InvalidInputReference('Input References to Arrays of input files are currently not supported.\n' '"{}" is an array of files and can not be resolved for input references:' '\n{}'.format(input_identifier, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_directory(attributes, input_directory, input_identifier, input_reference): """ Returns the attributes in demand of the input directory. :param attri...
if input_directory['isArray']: raise InvalidInputReference('Input References to Arrays of input directories are currently not supported.\n' 'input directory "{}" is an array of directories and can not be resolved for input' 'references...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_input_reference(reference, inputs_to_reference): """ Replaces a given input_reference by a string extracted from inputs_to_reference. :param referenc...
if not reference.startswith('{}inputs.'.format(INPUT_REFERENCE_START)): raise InvalidInputReference('An input reference must have the following form' '"$(inputs.<input_name>[.<attribute>]".\n' 'The invalid reference is: "{}"'.format(re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_input_references(to_resolve, inputs_to_reference): """ Resolves input references given in the string to_resolve by using the inputs_to_reference. See...
splitted = split_input_references(to_resolve) result = [] for part in splitted: if is_input_reference(part): result.append(str(resolve_input_reference(part, inputs_to_reference))) else: result.append(part) return ''.join(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 TemplateValidator(value): """Try to compile a string into a Django template"""
try: Template(value) except Exception as e: raise ValidationError( _("Cannot compile template (%(exception)s)"), params={"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 merge( fname1, fname2, dfilter1=None, dfilter2=None, has_header1=True, has_header2=True, frow1=0, frow2=0, ofname=None, ocols=None, ): r""" Merge two comma-s...
# pylint: disable=R0913,R0914 iomm_ex = pexdoc.exh.addex( RuntimeError, "Combined columns in data files and output columns are different" ) # Read and validate file 1 obj1 = CsvFile(fname=fname1, dfilter=dfilter1, has_header=has_header1, frow=frow1) # Read and validate file 2 obj2 =...
<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_lbry_api_function_docs(url=LBRY_API_RAW_JSON_URL): """ Scrapes the given URL to a page in JSON format to obtain the documentation for the LBRY API :param...
try: # Grab the page content docs_page = urlopen(url) # Read the contents of the actual url we grabbed and decode them into UTF-8 contents = docs_page.read().decode("utf-8") # Return the contents loaded as JSON return loads(contents) # If we get an except...
<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_method_definition(func): """ Generates the body for the given function :param dict func: dict of a JSON-Formatted function as defined by the API doc...
indent = 4 # initial definition method_definition = (" " * indent) + "def " + func["name"] # Here we just create a queue and put all the parameters # into the queue in the order that they were given, params_required = [ param for param in func["arguments"] if param["is_required"] ...
<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_lbryd_wrapper(url=LBRY_API_RAW_JSON_URL, read_file=__LBRYD_BASE_FPATH__, write_file=LBRYD_FPATH): """ Generates the actual functions for lbryd_api.p...
functions = get_lbry_api_function_docs(url) # Open the actual file for appending with open(write_file, 'w') as lbry_file: lbry_file.write("# This file was generated at build time using the generator function\n") lbry_file.write("# You may edit but do so with caution\n") with ope...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_nii(strPathIn, varSzeThr=5000.0): """ Load nii file. Parameters strPathIn : str Path to nii file to load. varSzeThr : float If the nii file is larger th...
# Load nii file (this does not load the data into memory yet): objNii = nb.load(strPathIn) # Get size of nii file: varNiiSze = os.path.getsize(strPathIn) # Convert to MB: varNiiSze = np.divide(float(varNiiSze), 1000000.0) # Load volume-by-volume or all at once, depending on file size: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_res_prm(lstFunc, lstFlsMsk=None): """Load result parameters from multiple nii files, with optional mask. Parameters lstFunc : list, list of str with fil...
# load parameter/functional maps into a list lstPrm = [] for ind, path in enumerate(lstFunc): aryFnc = load_nii(path)[0].astype(np.float32) if aryFnc.ndim == 3: lstPrm.append(aryFnc) # handle cases where nii array is 4D, in this case split arrays up in # 3D arra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_crt_to_pol(aryXCrds, aryYrds): """Remap coordinates from cartesian to polar Parameters aryXCrds : 1D numpy array Array with x coordinate values. aryYrds ...
aryRad = np.sqrt(aryXCrds**2+aryYrds**2) aryTht = np.arctan2(aryYrds, aryXCrds) return aryTht, aryRad
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def map_pol_to_crt(aryTht, aryRad): """Remap coordinates from polar to cartesian Parameters aryTht : 1D numpy array Angle of coordinates aryRad : 1D numpy array ...
aryXCrds = aryRad * np.cos(aryTht) aryYrds = aryRad * np.sin(aryTht) return aryXCrds, aryYrds
<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_near_pol_ang(aryEmpPlrAng, aryExpPlrAng): """Return index of nearest expected polar angle. Parameters aryEmpPlrAng : 1D numpy array Empirically found po...
dist = np.abs(np.subtract(aryEmpPlrAng[:, None], aryExpPlrAng[None, :])) return np.argmin(dist, axis=-1), np.min(dist, axis=-1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rmp_rng(aryVls, varNewMin, varNewMax, varOldThrMin=None, varOldAbsMax=None): """Remap values in an array from one range to another. Parameters aryVls : 1D nu...
if varOldThrMin is None: varOldMin = aryVls.min() else: varOldMin = varOldThrMin if varOldAbsMax is None: varOldMax = aryVls.max() else: varOldMax = varOldAbsMax aryNewVls = np.empty((aryVls.shape), dtype=aryVls.dtype) for ind, val in enumerate(aryVls): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rmp_deg_pixel_xys(vecX, vecY, vecPrfSd, tplPngSize, varExtXmin, varExtXmax, varExtYmin, varExtYmax): """Remap x, y, sigma parameters from degrees to pixel. P...
# Remap modelled x-positions of the pRFs: vecXpxl = rmp_rng(vecX, 0.0, (tplPngSize[0] - 1), varOldThrMin=varExtXmin, varOldAbsMax=varExtXmax) # Remap modelled y-positions of the pRFs: vecYpxl = rmp_rng(vecY, 0.0, (tplPngSize[1] - 1), varOldThrMin=varExtYmin, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cnvl_2D_gauss(idxPrc, aryMdlParamsChnk, arySptExpInf, tplPngSize, queOut, strCrd='crt'): """Spatially convolve input with 2D Gaussian model. Parameters idxPr...
# Number of combinations of model parameters in the current chunk: varChnkSze = aryMdlParamsChnk.shape[0] # Number of conditions / time points of the input data varNumLstAx = arySptExpInf.shape[-1] # Output array with results of convolution: aryOut = np.zeros((varChnkSze, varNumLstAx)) #...
<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(self, checksum, revision=None): """ Process a new revision and detect a revert if it occurred. Note that you can pass whatever you like as `revision`...
revert = None if checksum in self: # potential revert reverteds = list(self.up_to(checksum)) if len(reverteds) > 0: # If no reverted revisions, this is a noop revert = Revert(revision, reverteds, self[checksum]) self.insert(checksum, revision) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def funcSmthSpt(aryFuncChnk, varSdSmthSpt): """Apply spatial smoothing to the input data. Parameters aryFuncChnk : np.array TODO varSdSmthSpt : float (?) Extent ...
varNdim = aryFuncChnk.ndim # Number of time points in this chunk: varNumVol = aryFuncChnk.shape[-1] # Loop through volumes: if varNdim == 4: for idxVol in range(0, varNumVol): aryFuncChnk[:, :, :, idxVol] = gaussian_filter( aryFuncChnk[:, :, :, idxVol], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def funcSmthTmp(aryFuncChnk, varSdSmthTmp): """Apply temporal smoothing to fMRI data & pRF time course models. Parameters aryFuncChnk : np.array TODO varSdSmthTm...
# For the filtering to perform well at the ends of the time series, we # set the method to 'nearest' and place a volume with mean intensity # (over time) at the beginning and at the end. aryFuncChnkMean = np.mean(aryFuncChnk, axis=1, keepdims=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prep_models(aryPrfTc, varSdSmthTmp=2.0, lgcPrint=True): """ Prepare pRF model time courses. Parameters aryPrfTc : np.array 4D numpy array with pRF time cours...
if lgcPrint: print('------Prepare pRF time course models') # Define temporal smoothing of pRF time course models def funcSmthTmp(aryPrfTc, varSdSmthTmp, lgcPrint=True): """Apply temporal smoothing to fMRI data & pRF time course models. Parameters ---------- aryPrfT...
<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(self,style): """ what's the value of a style at the current stack level"""
level = len(self.stack) -1 while level >= 0: if style in self.stack[level]: return self.stack[level][style] else: level = level - 1 return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enforce_type(self, attr, val): """converts a value to the attribute's type"""
if not attr in self.types: return utfstr(val) elif self.types[attr] == 'int': return int(float(val)) elif self.types[attr] == 'float': return float(val) else: return utfstr(val)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, style={}): """overrides style values at the current stack level"""
_style = {} for attr in style: if attr in self.cmds and not style[attr] in self.cmds[attr]: print 'WARNING: ESC/POS PRINTING: ignoring invalid value: '+utfstr(style[attr])+' for style: '+utfstr(attr) else: self.stack[-1][attr] = self.enforce_type(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_escpos(self): """ converts the current style to an escpos command string """
cmd = '' ordered_cmds = self.cmds.keys() ordered_cmds.sort(lambda x,y: cmp(self.cmds[x]['_order'], self.cmds[y]['_order'])) for style in ordered_cmds: cmd += self.cmds[style][self.get(style)] return cmd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_inline(self,stylestack=None): """ starts an inline entity with an optional style definition """
self.stack.append('inline') if self.dirty: self.escpos._raw(' ') if stylestack: self.style(stylestack)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_block(self,stylestack=None): """ starts a block entity with an optional style definition """
if self.dirty: self.escpos._raw('\n') self.dirty = False self.stack.append('block') if stylestack: self.style(stylestack)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pre(self,text): """ puts a string of text in the entity keeping the whitespace intact """
if text: self.escpos.text(text) self.dirty = 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 text(self,text): """ puts text in the entity. Whitespace and newlines are stripped to single spaces. """
if text: text = utfstr(text) text = text.strip() text = re.sub('\s+',' ',text) if text: self.dirty = True self.escpos.text(text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_image_size(self, size): """ Check and fix the size of the image to 32 bits """
if size % 32 == 0: return (0, 0) else: image_border = 32 - (size % 32) if (image_border % 2) == 0: return (image_border / 2, image_border / 2) else: return (image_border / 2, (image_border / 2) + 1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convert_image(self, im): """ Parse image and prepare it to a printable format """
pixels = [] pix_line = "" im_left = "" im_right = "" switch = 0 img_size = [ 0, 0 ] if im.size[0] > 512: print "WARNING: Image is wider than 512 and could be truncated at print time " if im.size[1] > 255: raise ImageSizeErr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image(self,path_img): """ Open image file """
im_open = Image.open(path_img) im = im_open.convert("RGB") # Convert the RGB image in printable image pix_line, img_size = self._convert_image(im) self._print_image(pix_line, img_size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qr(self,text): """ Print QR Code for the provided string """
qr_code = qrcode.QRCode(version=4, box_size=4, border=1) qr_code.add_data(text) qr_code.make(fit=True) qr_img = qr_code.make_image() im = qr_img._img.convert("RGB") # Convert the RGB image in printable image self._convert_image(im)
<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(self,txt): """ Print Utf8 encoded alpha-numeric text """
if not txt: return try: txt = txt.decode('utf-8') except: try: txt = txt.decode('utf-16') except: pass self.extra_chars = 0 def encode_char(char): """ Encodes a s...
<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(self, align='left', font='a', type='normal', width=1, height=1): """ Set text properties """
# Align if align.upper() == "CENTER": self._raw(TXT_ALIGN_CT) elif align.upper() == "RIGHT": self._raw(TXT_ALIGN_RT) elif align.upper() == "LEFT": self._raw(TXT_ALIGN_LT) # Font if font.upper() == "B": self._raw(TXT_FONT_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 cashdraw(self, pin): """ Send pulse to kick the cash drawer """
if pin == 2: self._raw(CD_KICK_2) elif pin == 5: self._raw(CD_KICK_5) else: raise CashDrawerError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def control(self, ctl): """ Feed control sequences """
if ctl.upper() == "LF": self._raw(CTL_LF) elif ctl.upper() == "FF": self._raw(CTL_FF) elif ctl.upper() == "CR": self._raw(CTL_CR) elif ctl.upper() == "HT": self._raw(CTL_HT) elif ctl.upper() == "VT": self._raw(CTL_VT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """ Search device on USB tree and set is as escpos device """
self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct) if self.device is None: raise NoDeviceError() try: if self.device.is_kernel_driver_active(self.interface): self.device.detach_kernel_driver(self.interface) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """ Open TCP socket and set it as escpos device """
self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.device.connect((self.host, self.port)) if self.device is None: print "Could not open socket for %s" % self.host
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pinyin_generator(chars, format): """Generate pinyin for chars, if char is not chinese character, itself will be returned. Chars must be unicode list. """
for char in chars: key = "%X" % ord(char) pinyin = pinyin_dict.get(key, char) tone = pinyin_tone.get(key, 0) if tone == 0 or format == "strip": pass elif format == "numerical": pinyin += str(tone) elif format == "diacritical": # 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 get(s, delimiter='', format="diacritical"): """Return pinyin of string, the string must be unicode """
return delimiter.join(_pinyin_generator(u(s), format=format))
<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_initial(s, delimiter=' '): """Return the 1st char of pinyin of string, the string must be unicode """
initials = (p[0] for p in _pinyin_generator(u(s), format="strip")) return delimiter.join(initials)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init(): ''' Load in the Chinese-English dictionary. This takes 1-2 seconds. It is done when the other functions are used, but this is public since preloading sometimes makes sense. ''' global dictionaries, trees dictionaries = { 'traditional': {}, 'simplified': {} } ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def translate_word(word, dictionary=['simplified']): ''' Return the set of translations for a single character or word, if available. ''' if not dictionaries: init() for d in dictionary: if word in dictionaries[d]: return dictionaries[d][word] return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _words_at_the_beginning(word, tree, prefix=""): ''' We return all portions of the tree corresponding to the beginning of `word`. This is used recursively, so we pass the prefix so we can return meaningful words+translations. ''' l = [] if "" in tree: l.append([prefix, tree[""]]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def all_phrase_translations(phrase): ''' Return the set of translations for all possible words in a full phrase. Chinese is sometimes ambiguous. We do not attempt to disambiguate, or handle unknown letters especially well. Full parsing is left to upstream logic. ''' if not trees: ini...
<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_status_key(self, instance): """Generates a key used to set a status on a field"""
key_id = "inst_%s" % id(instance) if instance.pk is None else instance.pk return "%s.%s-%s-%s" % (instance._meta.app_label, get_model_name(instance), key_id, self.field.name)
<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_status(self, instance): """Retrives a status of a field from cache. Fields in state 'error' and 'complete' will not retain the status after the call. """
status_key, status = self._get_status(instance) if status['state'] in ['complete', 'error']: cache.delete(status_key) return status
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_status(self, instance, status): """Sets the field status for up to 5 minutes."""
status_key = self.get_status_key(instance) cache.set(status_key, status, timeout=300)
<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_mode(self, old_mode=None): """Returns output mode. If `mode` not set it will try to guess best mode, or next best mode comparing to old mode """
if self.mode is not None: return self.mode assert self.can_write, "This format does not have a supported output mode." if old_mode is None: return self.output_modes[0] if old_mode in self.output_modes: return old_mode # now let's get best mode...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send(self, data, msg_type='ok', silent=False): """ Send a response to the frontend and return an execute message @param data: response to send @param msg_ty...
# Data to send back if data is not None: # log the message try: self._klog.debug(u"msg to frontend (%d): %.160s...", silent, data) except Exception as e: self._klog.warn(u"can't log response: %s", e) # send it to the fronte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False): """ Method called to execute a cell """
self._klog.info("[%.30s] [%d] [%s]", code, silent, user_expressions) # Split lines and remove empty lines & comments code_noc = [line.strip() for line in code.split('\n') if line and line[0] != '#'] if not code_noc: return self._send(None) # Pro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_inspect(self, code, cursor_pos, detail_level=0): """ Method called on help requests """
self._klog.info("{%s}", code[cursor_pos:cursor_pos+10]) # Find the token for which help is requested token, start = token_at_cursor(code, cursor_pos) self._klog.debug("token={%s} {%d}", token, detail_level) # Find the help for this token if not is_magic(token, start, 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 do_complete(self, code, cursor_pos): """ Method called on autocompletion requests """
self._klog.info("{%s}", code[cursor_pos:cursor_pos+10]) token, start = token_at_cursor(code, cursor_pos) tkn_low = token.lower() if is_magic(token, start, code): matches = [k for k in magics.keys() if k.startswith(tkn_low)] else: matches = [sparql_names[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data_msglist( msglist ): """ Return a Jupyter display_data message, in both HTML & text formats, by joining together all passed messages. @param msglist (ite...
txt = html = u'' for msg, css in msglist: if is_collection(msg): msg = msg[0].format(*msg[1:]) html += div( escape(msg).replace('\n','<br/>'), css=css or 'msg' ) txt += msg + "\n" return { 'data': {'text/html' : div(html), 'text/plain' : txt }, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copyresource( resource, filename, destdir ): """ Copy a resource file to a destination """
data = pkgutil.get_data(resource, os.path.join('resources',filename) ) #log.info( "Installing %s", os.path.join(destdir,filename) ) with open( os.path.join(destdir,filename), 'wb' ) as fp: fp.write(data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_kernel_resources( destdir, resource=PKGNAME, files=None ): """ Copy the resource files to the kernelspec folder. """
if files is None: files = ['logo-64x64.png', 'logo-32x32.png'] for filename in files: try: copyresource( resource, filename, destdir ) except Exception as e: sys.stderr.write(str(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 install_custom_css( destdir, cssfile, resource=PKGNAME ): """ Add the kernel CSS to custom.css """
ensure_dir_exists( destdir ) custom = os.path.join( destdir, 'custom.css' ) prefix = css_frame_prefix(resource) # Check if custom.css already includes it. If so, let's remove it first exists = False if os.path.exists( custom ): with io.open(custom) as f: for line in 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 remove_custom_css(destdir, resource=PKGNAME ): """ Remove the kernel CSS from custom.css """
# Remove the inclusion in the main CSS if not os.path.isdir( destdir ): return False custom = os.path.join( destdir, 'custom.css' ) copy = True found = False prefix = css_frame_prefix(resource) with io.open(custom + '-new', 'wt') as fout: with io.open(custom) as fin: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html_elem(e, ct, withtype=False): """ Format a result element as an HTML table cell. @param e (list): a pair \c (value,type) @param ct (str): cell type (th...
# Header cell if ct == 'th': return '<th>{0}</th><th>{1}</th>'.format(*e) if withtype else '<th>{}</th>'.format(e) # Content cell if e[1] in ('uri', 'URIRef'): html = u'<{0} class=val><a href="{1}" target="_other">{2}</a></{0}>'.format(ct, e[0], escape(e[0])) else: html = u'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html_table(data, header=True, limit=None, withtype=False): """ Return a double iterable as an HTML table @param data (iterable): the data to format @param h...
if header and limit: limit += 1 ct = 'th' if header else 'td' rc = 'hdr' if header else 'odd' # import codecs # import datetime # with codecs.open( '/tmp/dump', 'w', encoding='utf-8') as f: # print( '************', datetime.datetime.now(), file=f ) # for n, row in enume...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jtype(c): """ Return the a string with the data type of a value, for JSON data """
ct = c['type'] return ct if ct != 'literal' else '{}, {}'.format(ct, c.get('xml:lang'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gtype(n): """ Return the a string with the data type of a value, for Graph data """
t = type(n).__name__ return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lang_match_json(row, hdr, accepted_languages): '''Find if the JSON row contains acceptable language data''' if not accepted_languages: return True languages = set([row[c].get('xml:lang') for c in hdr if c in row and row[c]['type'] == 'literal']) return (not languages) 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 lang_match_rdf(triple, accepted_languages): '''Find if the RDF triple contains acceptable language data''' if not accepted_languages: return True languages = set([n.language for n in triple if isinstance(n, Literal)]) return (not languages) or (languages & accepted_languages)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lang_match_xml(row, accepted_languages): '''Find if the XML row contains acceptable language data''' if not accepted_languages: return True column_languages = set() for elem in row: lang = elem[0].attrib.get(XML_LANG, None) if lang: column_languages.add(lang) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_json(result, cfg, **kwargs): """ Render to output a result in JSON format """
result = json.loads(result.decode('utf-8')) head = result['head'] if 'results' not in result: if 'boolean' in result: r = u'Result: {}'.format(result['boolean']) else: r = u'Unsupported result: \n' + unicode(result) return {'data': {'text/plain': 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 xml_row(row, lang): ''' Generator for an XML row ''' for elem in row: name = elem.get('name') child = elem[0] ftype = re.sub(r'\{[^}]+\}', '', child.tag) if ftype == 'literal': ftype = '{}, {}'.format(ftype, child.attrib.get(XML_LANG, 'none')) yiel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_xml(result, cfg, **kwargs): """ Render to output a result in XML format """
# Raw mode if cfg.dis == 'raw': return {'data': {'text/plain': result.decode('utf-8')}, 'metadata': {}} # Table try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET root = ET.fromstring(result) try: n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_graph(result, cfg, **kwargs): """ Render to output a result that can be parsed as an RDF graph """
# Mapping from MIME types to formats accepted by RDFlib rdflib_formats = {'text/rdf+n3': 'n3', 'text/turtle': 'turtle', 'application/x-turtle': 'turtle', 'text/turtle': 'turtle', 'application/rdf+xml': 'xml', ...
<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_logging( logfilename=None, level=None ): """ Set a logging configuration, with a rolling file appender. If passed a filename, use it as the logfile, else...
if logfilename is None: # Find the logging diectory logdir = os.environ.get( 'LOGDIR' ) if logdir is None: logdir = os.environ.get( 'LOGDIR_DEFAULT', tempfile.gettempdir() ) # Define the log filename basename = __name__.split('.')[-2] logfilename = os.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 smartfields_get_field_status(self, field_name): """A way to find out a status of a filed."""
manager = self._smartfields_managers.get(field_name, None) if manager is not None: return manager.get_status(self) return {'state': 'ready'}
<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_output_file(self, in_file, instance, field, **kwargs): """Creates a temporary file. With regular `FileSystemStorage` it does not need to be deleted, inst...
return NamedTemporaryFile(mode='rb', suffix='_%s_%s%s' % ( get_model_name(instance), field.name, self.get_ext()), delete=False)