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 normalize_list(self, text, cache=None): """ Get a canonical list representation of text, with words separated and reduced to their base forms. TODO: use the ...
words = [] analysis = self.analyze(text) for record in analysis: if not self.is_stopword_record(record): words.append(self.get_record_root(record)) if not words: # Don't discard stopwords if that's all you've got words = [self.get_reco...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_phrases(self, text): """ Given some text, extract phrases of up to 2 content words, and map their normalized form to the complete phrase. """
analysis = self.analyze(text) for pos1 in range(len(analysis)): rec1 = analysis[pos1] if not self.is_stopword_record(rec1): yield self.get_record_root(rec1), rec1[0] for pos2 in range(pos1 + 1, len(analysis)): rec2 = analysis[p...
<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_kana(text): """ Use MeCab to turn any text into its phonetic spelling, as katakana separated by spaces. """
records = MECAB.analyze(text) kana = [] for record in records: if record.pronunciation: kana.append(record.pronunciation) elif record.reading: kana.append(record.reading) else: kana.append(record.surface) return ' '.join(k for k in kana if k)
<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_record_pos(self, record): """ Given a record, get the word's part of speech. Here we're going to return MeCab's part of speech (written in Japanese), tho...
if self.is_stopword_record(record): return '~' + record.pos else: return record.pos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def untokenize(words): """ Untokenizing a text undoes the tokenizing operation, restoring punctuation and spaces to the places that people expect them to be. Ide...
text = ' '.join(words) step1 = text.replace("`` ", '"').replace(" ''", '"').replace('. . .', '...') step2 = step1.replace(" ( ", " (").replace(" ) ", ") ") step3 = re.sub(r' ([.,:;?!%]+)([ \'"`])', r"\1\2", step2) step4 = re.sub(r' ([.,:;?!%]+)$', r"\1", step3) step5 = step4.replace(" '", "'")....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def un_camel_case(text): r""" Splits apart words that are written in CamelCase. Bugs: - Non-ASCII characters are treated as lowercase letters, even if they are a...
revtext = text[::-1] pieces = [] while revtext: match = CAMEL_RE.match(revtext) if match: pieces.append(match.group(1)) revtext = revtext[match.end():] else: pieces.append(revtext) revtext = '' revstr = ' '.join(piece.strip(' _') 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 _word_badness(word): """ Assign a heuristic to possible outputs from Morphy. Minimizing this heuristic avoids incorrect stems. """
if word.endswith('e'): return len(word) - 2 elif word.endswith('ess'): return len(word) - 10 elif word.endswith('ss'): return len(word) - 4 else: return len(word)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def morphy_stem(word, pos=None): """ Get the most likely stem for a word. If a part of speech is supplied, the stem will be more accurate. Valid parts of speech ...
word = word.lower() if pos is not None: if pos.startswith('NN'): pos = 'n' elif pos.startswith('VB'): pos = 'v' elif pos.startswith('JJ'): pos = 'a' elif pos.startswith('RB'): pos = 'r' if pos is None and word.endswith('ing') o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_list(text): """ Get a list of word stems that appear in the text. Stopwords and an initial 'to' will be stripped, unless this leaves nothing in the...
pieces = [morphy_stem(word) for word in tokenize(text)] pieces = [piece for piece in pieces if good_lemma(piece)] if not pieces: return [text] if pieces[0] == 'to': pieces = pieces[1:] return pieces
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize_topic(topic): """ Get a canonical representation of a Wikipedia topic, which may include a disambiguation string in parentheses. Returns (name, dis...
# find titles of the form Foo (bar) topic = topic.replace('_', ' ') match = re.match(r'([^(]+) \(([^)]+)\)', topic) if not match: return normalize(topic), None else: return normalize(match.group(1)), 'n/' + match.group(2).strip(' _')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def key2elements(key): """split key to elements"""
# words = key.split('.') # if len(words) == 4: # return words # # there is a dot in object name # fieldword = words.pop(-1) # nameword = '.'.join(words[-2:]) # if nameword[-1] in ('"', "'"): # # The object name is in quotes # nameword = nameword[1:-1] # elements = wo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updateidf(idf, dct): """update idf using dct"""
for key in list(dct.keys()): if key.startswith('idf.'): idftag, objkey, objname, field = key2elements(key) if objname == '': try: idfobj = idf.idfobjects[objkey.upper()][0] except IndexError as e: idfobj = idf.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 fan_maxcfm(ddtt): """return the fan max cfm"""
if str(ddtt.Maximum_Flow_Rate).lower() == 'autosize': # str can fail with unicode chars :-( return 'autosize' else: m3s = float(ddtt.Maximum_Flow_Rate) return m3s2cfm(m3s)
<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_paths(version=None, iddname=None): """Get the install paths for EnergyPlus executable and weather files. We prefer to get the install path from the I...
try: eplus_exe, eplus_home = paths_from_iddname(iddname) except (AttributeError, TypeError, ValueError): eplus_exe, eplus_home = paths_from_version(version) eplus_weather = os.path.join(eplus_home, 'WeatherData') return eplus_exe, eplus_weather
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrapped_help_text(wrapped_func): """Decorator to pass through the documentation from a wrapped function. """
def decorator(wrapper_func): """The decorator. Parameters ---------- f : callable The wrapped function. """ wrapper_func.__doc__ = ('This method wraps the following method:\n\n' + pydoc.text.document(wrapped_func)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_run(run_id, run_data): """Prepare run inputs for one of multiple EnergyPlus runs. :param run_id: An ID number for naming the IDF. :param run_data: Tu...
idf, kwargs = run_data epw = idf.epw idf_dir = os.path.join('multi_runs', 'idf_%i' % run_id) os.mkdir(idf_dir) idf_path = os.path.join(idf_dir, 'in.idf') idf.saveas(idf_path) return (idf_path, epw), kwargs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(idf=None, weather=None, output_directory='', annual=False, design_day=False, idd=None, epmacro=False, expandobjects=False, readvars=False, output_prefix=N...
args = locals().copy() # get unneeded params out of args ready to pass the rest to energyplus.exe verbose = args.pop('verbose') idf = args.pop('idf') iddname = args.get('idd') if not isinstance(iddname, str): args.pop('idd') try: idf_path = os.path.abspath(idf.idfname) 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 parse_error(output_dir): """Add contents of stderr and eplusout.err and put it in the exception message. :param output_dir: str :return: str """
sys.stderr.seek(0) std_err = sys.stderr.read().decode('utf-8') err_file = os.path.join(output_dir, "eplusout.err") if os.path.isfile(err_file): with open(err_file, "r") as f: ep_err = f.read() else: ep_err = "<File not found>" message = "\r\n{std_err}\r\nContents of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def almostequal(first, second, places=7, printit=True): """ Test if two values are equal to a given number of places. This is based on python's unittest so may b...
if first == second: return True if round(abs(second - first), places) != 0: if printit: print(round(abs(second - first), places)) print("notalmost: %s != %s to %i places" % (first, second, places)) return False else: 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 newrawobject(data, commdct, key, block=None, defaultvalues=True): """Make a new object for the given key. Parameters data : Eplusdata object Data dictionary ...
dtls = data.dtls key = key.upper() key_i = dtls.index(key) key_comm = commdct[key_i] # set default values if defaultvalues: obj = [comm.get('default', [''])[0] for comm in key_comm] else: obj = ['' for comm in key_comm] if not block: inblock = ['does not start w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addthisbunch(bunchdt, data, commdct, thisbunch, theidf): """add a bunch to model. abunch usually comes from another idf file or it can be used to copy within...
key = thisbunch.key.upper() obj = copy.copy(thisbunch.obj) abunch = obj2bunch(data, commdct, obj) bunchdt[key].append(abunch) return abunch
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obj2bunch(data, commdct, obj): """make a new bunch object using the data object"""
dtls = data.dtls key = obj[0].upper() key_i = dtls.index(key) abunch = makeabunch(commdct, obj, key_i) return abunch
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getobject(bunchdt, key, name): """get the object if you have the key and the name returns a list of objects, in case you have more than one You should not ha...
# TODO : throw exception if more than one object, or return more objects idfobjects = bunchdt[key] if idfobjects: # second item in list is a unique ID unique_id = idfobjects[0].objls[1] theobjs = [idfobj for idfobj in idfobjects if idfobj[unique_id].upper() == name.upper(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __objecthasfields(bunchdt, data, commdct, idfobject, places=7, **kwargs): """test if the idf object has the field values in kwargs"""
for key, value in list(kwargs.items()): if not isfieldvalue( bunchdt, data, commdct, idfobject, key, value, places=places): return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iddofobject(data, commdct, key): """from commdct, return the idd of the object key"""
dtls = data.dtls i = dtls.index(key) return commdct[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 getextensibleindex(bunchdt, data, commdct, key, objname): """get the index of the first extensible item"""
theobject = getobject(bunchdt, key, objname) if theobject == None: return None theidd = iddofobject(data, commdct, key) extensible_i = [ i for i in range(len(theidd)) if 'begin-extensible' in theidd[i]] try: extensible_i = extensible_i[0] except IndexError: retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeextensibles(bunchdt, data, commdct, key, objname): """remove the extensible items in the object"""
theobject = getobject(bunchdt, key, objname) if theobject == None: return theobject theidd = iddofobject(data, commdct, key) extensible_i = [ i for i in range(len(theidd)) if 'begin-extensible' in theidd[i]] try: extensible_i = extensible_i[0] except IndexError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getfieldcomm(bunchdt, data, commdct, idfobject, fieldname): """get the idd comment for the field"""
key = idfobject.obj[0].upper() keyi = data.dtls.index(key) fieldi = idfobject.objls.index(fieldname) thiscommdct = commdct[keyi][fieldi] return thiscommdct
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_retaincase(bunchdt, data, commdct, idfobject, fieldname): """test if case has to be retained for that field"""
thiscommdct = getfieldcomm(bunchdt, data, commdct, idfobject, fieldname) return 'retaincase' in thiscommdct
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isfieldvalue(bunchdt, data, commdct, idfobj, fieldname, value, places=7): """test if idfobj.field == value"""
# do a quick type check # if type(idfobj[fieldname]) != type(value): # return False # takes care of autocalculate and real # check float thiscommdct = getfieldcomm(bunchdt, data, commdct, idfobj, fieldname) if 'type' in thiscommdct: if thiscommdct['type'][0] in ('real', 'integer'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getrefnames(idf, objname): """get the reference names for this object"""
iddinfo = idf.idd_info dtls = idf.model.dtls index = dtls.index(objname) fieldidds = iddinfo[index] for fieldidd in fieldidds: if 'field' in fieldidd: if fieldidd['field'][0].endswith('Name'): if 'reference' in fieldidd: return fieldidd['refer...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename(idf, objkey, objname, newname): """rename all the refrences to this objname"""
refnames = getrefnames(idf, objkey) for refname in refnames: objlists = getallobjlists(idf, refname) # [('OBJKEY', refname, fieldindexlist), ...] for refname in refnames: # TODO : there seems to be a duplication in this loop. Check. # refname appears in both loops ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zone_height_min2max(idf, zonename, debug=False): """zone height = max-min"""
zone = idf.getobject('ZONE', zonename) surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()] zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name] surf_xyzs = [eppy.function_helpers.getcoords(s) for s in zone_surfs] surf_xyzs = list(itertools.chain(*surf_xyzs)) surf_zs = [z for x, y,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zone_floor2roofheight(idf, zonename, debug=False): """zone floor to roof height"""
zone = idf.getobject('ZONE', zonename) surfs = idf.idfobjects['BuildingSurface:Detailed'.upper()] zone_surfs = [s for s in surfs if s.Zone_Name == zone.Name] floors = [s for s in zone_surfs if s.Surface_Type.upper() == 'FLOOR'] roofs = [s for s in zone_surfs if s.Surface_Type.upper() == 'ROOF'] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setiddname(cls, iddname, testing=False): """ Set the path to the EnergyPlus IDD for the version of EnergyPlus which is to be used by eppy. Parameters iddname...
if cls.iddname == None: cls.iddname = iddname cls.idd_info = None cls.block = None elif cls.iddname == iddname: pass else: if testing == False: errortxt = "IDD file is set to: %s" % (cls.iddname,) raise ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setidd(cls, iddinfo, iddindex, block, idd_version): """Set the IDD to be used by eppy. Parameters iddinfo : list Comments and metadata about fields in the ID...
cls.idd_info = iddinfo cls.block = block cls.idd_index = iddindex cls.idd_version = idd_version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initread(self, idfname): """ Use the current IDD and read an IDF from file. If the IDD has not yet been initialised then this is done first. Parameters idf_n...
with open(idfname, 'r') as _: # raise nonexistent file error early if idfname doesn't exist pass iddfhandle = StringIO(iddcurrent.iddtxt) if self.getiddname() == None: self.setiddname(iddfhandle) self.idfname = idfname self.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initreadtxt(self, idftxt): """ Use the current IDD and read an IDF from text data. If the IDD has not yet been initialised then this is done first. Parameter...
iddfhandle = StringIO(iddcurrent.iddtxt) if self.getiddname() == None: self.setiddname(iddfhandle) idfhandle = StringIO(idftxt) self.idfname = idfhandle self.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self): """ Read the IDF file and the IDD file. If the IDD file had already been read, it will not be read again. Read populates the following data struc...
if self.getiddname() == None: errortxt = ("IDD file needed to read the idf file. " "Set it using IDF.setiddname(iddfile)") raise IDDNotSetError(errortxt) readout = idfreader1( self.idfname, self.iddname, self, commdct=self.idd_info...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initnew(self, fname): """ Use the current IDD and create a new empty IDF. If the IDD has not yet been initialised then this is done first. Parameters fname :...
iddfhandle = StringIO(iddcurrent.iddtxt) if self.getiddname() == None: self.setiddname(iddfhandle) idfhandle = StringIO('') self.idfname = idfhandle self.read() if fname: self.idfname = fname
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newidfobject(self, key, aname='', defaultvalues=True, **kwargs): """ Add a new idfobject to the model. If you don't specify a value for a field, the default ...
obj = newrawobject(self.model, self.idd_info, key, block=self.block, defaultvalues=defaultvalues) abunch = obj2bunch(self.model, self.idd_info, obj) if aname: warnings.warn("The aname parameter should no longer be used.", UserWarning) namebu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeidfobject(self, idfobject): """Remove an IDF object from the IDF. Parameters idfobject : EpBunch object The IDF object to remove. """
key = idfobject.key.upper() self.idfobjects[key].remove(idfobject)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copyidfobject(self, idfobject): """Add an IDF object to the IDF. Parameters idfobject : EpBunch object The IDF object to remove. This usually comes from anot...
return addthisbunch(self.idfobjects, self.model, self.idd_info, idfobject, self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getextensibleindex(self, key, name): """ Get the index of the first extensible item. Only for internal use. # TODO : hide this Parameters key : str The type ...
return getextensibleindex( self.idfobjects, self.model, self.idd_info, key, 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 removeextensibles(self, key, name): """ Remove extensible items in the object of key and name. Only for internal use. # TODO : hide this Parameters key : str...
return removeextensibles( self.idfobjects, self.model, self.idd_info, key, 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 idfstr(self): """String representation of the IDF. Returns ------- str """
if self.outputtype == 'standard': astr = '' else: astr = self.model.__repr__() if self.outputtype == 'standard': astr = '' dtls = self.model.dtls for objname in dtls: for obj in self.idfobjects[objname]: ...
<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, filename=None, lineendings='default', encoding='latin-1'): """ Save the IDF as a text file with the optional filename passed, or with the current ...
if filename is None: filename = self.idfname s = self.idfstr() if lineendings == 'default': system = platform.system() s = '!- {} Line endings \n'.format(system) + s slines = s.splitlines() s = os.linesep.join(slines) elif line...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def saveas(self, filename, lineendings='default', encoding='latin-1'): """ Save the IDF as a text file with the filename passed. Parameters filename : str Filepa...
self.idfname = filename self.save(filename, lineendings, encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def savecopy(self, filename, lineendings='default', encoding='latin-1'): """Save a copy of the file with the filename passed. Parameters filename : str Filepath ...
self.save(filename, lineendings, encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, **kwargs): """ Run an IDF file with a given EnergyPlus weather file. This is a wrapper for the EnergyPlus command line interface. Parameters **kwar...
# write the IDF to the current directory self.saveas('in.idf') # if `idd` is not passed explicitly, use the IDF.iddname idd = kwargs.pop('idd', self.iddname) epw = kwargs.pop('weather', self.epw) try: run(self, weather=epw, idd=idd, **kwargs) finally:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getoneblock(astr, start, end): """get the block bounded by start and end doesn't work for multiple blocks"""
alist = astr.split(start) astr = alist[-1] alist = astr.split(end) astr = alist[0] return astr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def myreplace(astr, thefind, thereplace): """in string astr replace all occurences of thefind with thereplace"""
alist = astr.split(thefind) new_s = alist.split(thereplace) return new_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 fsliceafter(astr, sub): """Return the slice after at sub in string astr"""
findex = astr.find(sub) return astr[findex + len(sub):]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_str2file(pathname, astr): """writes a string to file"""
fname = pathname fhandle = open(fname, 'wb') fhandle.write(astr) fhandle.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_simpletable(table): """test if the table has only strings in the cells"""
tds = table('td') for td in tds: if td.contents != []: td = tdbr2EOL(td) if len(td.contents) == 1: thecontents = td.contents[0] if not isinstance(thecontents, NavigableString): return False else: ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table2matrix(table): """convert a table to a list of lists - a 2D matrix"""
if not is_simpletable(table): raise NotSimpleTable("Not able read a cell in the table as a string") rows = [] for tr in table('tr'): row = [] for td in tr('td'): td = tdbr2EOL(td) # convert any '<br>' in the td to line ending try: row.append(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table2val_matrix(table): """convert a table to a list of lists - a 2D matrix Converts numbers to float"""
if not is_simpletable(table): raise NotSimpleTable("Not able read a cell in the table as a string") rows = [] for tr in table('tr'): row = [] for td in tr('td'): td = tdbr2EOL(td) try: val = td.contents[0] except IndexError: ...
<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_name(soup_obj): """checks if soup_obj is really a soup object or just a string If it has a name it is a soup object"""
try: name = soup_obj.name if name == None: return False return True except AttributeError: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_ntgrid(grid): """make a named tuple grid [["", "a b", "b c", "c d"], ["x y", 1, 2, 3 ], ["y z", 4, 5, 6 ], ["z z", 7, 8, 9 ],] will return ntcol(x_y=nt...
hnames = [_nospace(n) for n in grid[0][1:]] vnames = [_nospace(row[0]) for row in grid[1:]] vnames_s = " ".join(vnames) hnames_s = " ".join(hnames) ntcol = collections.namedtuple('ntcol', vnames_s) ntrow = collections.namedtuple('ntrow', hnames_s) rdict = [dict(list(zip(hnames, row[1:]))) 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 onlylegalchar(name): """return only legal chars"""
legalchar = ascii_letters + digits + ' ' return ''.join([s for s in name[:] if s in legalchar])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intinlist(lst): """test if int in list"""
for item in lst: try: item = int(item) return True except ValueError: pass return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replaceint(fname, replacewith='%s'): """replace int in lst"""
words = fname.split() for i, word in enumerate(words): try: word = int(word) words[i] = replacewith except ValueError: pass return ' '.join(words)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleaniddfield(acomm): """make all the keys lower case"""
for key in list(acomm.keys()): val = acomm[key] acomm[key.lower()] = val for key in list(acomm.keys()): val = acomm[key] if key != key.lower(): acomm.pop(key) return acomm
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makecsvdiffs(thediffs, dtls, n1, n2): """return the csv to be displayed"""
def ishere(val): if val == None: return "not here" else: return "is here" rows = [] rows.append(['file1 = %s' % (n1, )]) rows.append(['file2 = %s' % (n2, )]) rows.append('') rows.append(theheader(n1, n2)) keys = list(thediffs.keys()) # ensures sorting...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def printcsv(csvdiffs): """print the csv"""
for row in csvdiffs: print(','.join([str(cell) for cell in row]))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def heading2table(soup, table, row): """add heading row to table"""
tr = Tag(soup, name="tr") table.append(tr) for attr in row: th = Tag(soup, name="th") tr.append(th) th.append(attr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def row2table(soup, table, row): """ad a row to the table"""
tr = Tag(soup, name="tr") table.append(tr) for attr in row: td = Tag(soup, name="td") tr.append(td) td.append(attr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def printhtml(csvdiffs): """print the html"""
soup = BeautifulSoup() html = Tag(soup, name="html") para1 = Tag(soup, name="p") para1.append(csvdiffs[0][0]) para2 = Tag(soup, name="p") para2.append(csvdiffs[1][0]) table = Tag(soup, name="table") table.attrs.update(dict(border="1")) soup.append(html) html.append(para1) 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 extendlist(lst, i, value=''): """extend the list so that you have i-th value"""
if i < len(lst): pass else: lst.extend([value, ] * (i - len(lst) + 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 addfunctions(abunch): """add functions to epbunch"""
key = abunch.obj[0].upper() #----------------- # TODO : alternate strategy to avoid listing the objkeys in snames # check if epbunch has field "Zone_Name" or "Building_Surface_Name" # and is in group u'Thermal Zones and Surfaces' # then it is likely to be a surface. # of course we need to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getrange(bch, fieldname): """get the ranges for this field"""
keys = ['maximum', 'minimum', 'maximum<', 'minimum>', 'type'] index = bch.objls.index(fieldname) fielddct_orig = bch.objidd[index] fielddct = copy.deepcopy(fielddct_orig) therange = {} for key in keys: therange[key] = fielddct.setdefault(key, None) if therange['type']: thera...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkrange(bch, fieldname): """throw exception if the out of range"""
fieldvalue = bch[fieldname] therange = bch.getrange(fieldname) if therange['maximum'] != None: if fieldvalue > therange['maximum']: astr = "Value %s is not less or equal to the 'maximum' of %s" astr = astr % (fieldvalue, therange['maximum']) raise RangeError(astr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getfieldidd_item(bch, fieldname, iddkey): """return an item from the fieldidd, given the iddkey will return and empty list if it does not have the iddkey or ...
fieldidd = getfieldidd(bch, fieldname) try: return fieldidd[iddkey] except KeyError as e: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isequal(bch, fieldname, value, places=7): """return True if the field is equal to value"""
def equalalphanumeric(bch, fieldname, value): if bch.get_retaincase(fieldname): return bch[fieldname] == value else: return bch[fieldname].upper() == value.upper() fieldidd = bch.getfieldidd(fieldname) try: ftype = fieldidd['type'][0] if ftype in ['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_referenced_object(referring_object, fieldname): """ Get an object referred to by a field in another object. For example an object of type Construction ha...
idf = referring_object.theidf object_list = referring_object.getfieldidd_item(fieldname, u'object-list') for obj_type in idf.idfobjects: for obj in idf.idfobjects[obj_type]: valid_object_lists = obj.getfieldidd_item("Name", u'reference') if set(object_list).intersection(set(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isequal(self, fieldname, value, places=7): """return True if the field == value Will retain case if get_retaincase == True for real value will compare to dec...
return isequal(self, fieldname, value, places=places)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makename2refdct(commdct): """make the name2refs dict in the idd_index"""
refdct = {} for comm in commdct: # commdct is a list of dict try: idfobj = comm[0]['idfobj'].upper() field1 = comm[1] if 'Name' in field1['field']: references = field1['reference'] refdct[idfobj] = references except (KeyError, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makeref2namesdct(name2refdct): """make the ref2namesdct in the idd_index"""
ref2namesdct = {} for key, values in name2refdct.items(): for value in values: ref2namesdct.setdefault(value, set()).add(key) return ref2namesdct
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ref2names2commdct(ref2names, commdct): """embed ref2names into commdct"""
for comm in commdct: for cdct in comm: try: refs = cdct['object-list'][0] validobjects = ref2names[refs] cdct.update({'validobjects':validobjects}) except KeyError as e: continue return commdct
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def area(poly): """Calculation of zone area"""
poly_xy = [] num = len(poly) for i in range(num): poly[i] = poly[i][0:2] + (0,) poly_xy.append(poly[i]) return surface.area(poly)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prevnode(edges, component): """get the pervious component in the loop"""
e = edges c = component n2c = [(a, b) for a, b in e if type(a) == tuple] c2n = [(a, b) for a, b in e if type(b) == tuple] node2cs = [(a, b) for a, b in e if b == c] c2nodes = [] for node2c in node2cs: c2node = [(a, b) for a, b in c2n if b == node2c[0]] if len(c2node) == 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getcoords(ddtt): """return the coordinates of the surface"""
n_vertices_index = ddtt.objls.index('Number_of_Vertices') first_x = n_vertices_index + 1 # X of first coordinate pts = ddtt.obj[first_x:] return list(grouper(3, pts))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buildingname(ddtt): """return building name"""
idf = ddtt.theidf building = idf.idfobjects['building'.upper()][0] return building.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 cleanupversion(ver): """massage the version number so it matches the format of install folder"""
lst = ver.split(".") if len(lst) == 1: lst.extend(['0', '0']) elif len(lst) == 2: lst.extend(['0']) elif len(lst) > 2: lst = lst[:3] lst[2] = '0' # ensure the 3rd number is 0 cleanver = '.'.join(lst) return cleanver
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getiddfile(versionid): """find the IDD file of the E+ installation"""
vlist = versionid.split('.') if len(vlist) == 1: vlist = vlist + ['0', '0'] elif len(vlist) == 2: vlist = vlist + ['0'] ver_str = '-'.join(vlist) eplus_exe, _ = eppy.runner.run_functions.install_paths(ver_str) eplusfolder = os.path.dirname(eplus_exe) iddfile = '{}/Energy+....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initdict(self, fname): """create a blank dictionary"""
if isinstance(fname, Idd): self.dt, self.dtls = fname.dt, fname.dtls return self.dt, self.dtls astr = mylib2.readfile(fname) nocom = removecomment(astr, '!') idfst = nocom alist = idfst.split(';') lss = [] for element in alist: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makedict(self, dictfile, fnamefobject): """stuff file data into the blank dictionary"""
#fname = './exapmlefiles/5ZoneDD.idf' #fname = './1ZoneUncontrolled.idf' if isinstance(dictfile, Idd): localidd = copy.deepcopy(dictfile) dt, dtls = localidd.dt, localidd.dtls else: dt, dtls = self.initdict(dictfile) # astr = mylib2.readfile(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 replacenode(self, othereplus, node): """replace the node here with the node from othereplus"""
node = node.upper() self.dt[node.upper()] = othereplus.dt[node.upper()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add2node(self, othereplus, node): """add the node here with the node from othereplus this will potentially have duplicates"""
node = node.upper() self.dt[node.upper()] = self.dt[node.upper()] + \ othereplus.dt[node.upper()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getrefs(self, reflist): """ reflist is got from getobjectref in parse_idd.py getobjectref returns a dictionary. reflist is an item in the dictionary getrefs ...
alist = [] for element in reflist: if element[0].upper() in self.dt: for elm in self.dt[element[0].upper()]: alist.append(elm[element[1]]) return alist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dropnodes(edges): """draw a graph without the nodes"""
newedges = [] added = False for edge in edges: if bothnodes(edge): newtup = (edge[0][0], edge[1][0]) newedges.append(newtup) added = True elif firstisnode(edge): for edge1 in edges: if edge[0] == edge1[1]: 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 edges2nodes(edges): """gather the nodes from the edges"""
nodes = [] for e1, e2 in edges: nodes.append(e1) nodes.append(e2) nodedict = dict([(n, None) for n in nodes]) justnodes = list(nodedict.keys()) # justnodes.sort() justnodes = sorted(justnodes, key=lambda x: str(x[0])) return justnodes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makediagram(edges): """make the diagram with the edges"""
graph = pydot.Dot(graph_type='digraph') nodes = edges2nodes(edges) epnodes = [(node, makeanode(node[0])) for node in nodes if nodetype(node)=="epnode"] endnodes = [(node, makeendnode(node[0])) for node in nodes if nodetype(node)=="EndNode"] epbr = [(node, makeabranch(node)) for no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makebranchcomponents(data, commdct, anode="epnode"): """return the edges jointing the components of a branch"""
alledges = [] objkey = 'BRANCH' cnamefield = "Component %s Name" inletfield = "Component %s Inlet Node Name" outletfield = "Component %s Outlet Node Name" numobjects = len(data.dt[objkey]) cnamefields = loops.repeatingfields(data, commdct, objkey, cnamefield) inletfields = loops.repea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getedges(fname, iddfile): """return the edges of the idf file fname"""
data, commdct, _idd_index = readidf.readdatacommdct(fname, iddfile=iddfile) edges = makeairplantloop(data, commdct) return edges
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeblanklines(astr): """remove the blank lines in astr"""
lines = astr.splitlines() lines = [line for line in lines if line.strip() != ""] return "\n".join(lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _readfname(fname): """copied from extractidddata below. It deals with all the types of fnames"""
try: if isinstance(fname, (file, StringIO)): astr = fname.read() else: astr = open(fname, 'rb').read() except NameError: if isinstance(fname, (FileIO, StringIO)): astr = fname.read() else: astr = mylib2.readfile(fname) return a...
<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_idd_index(extract_func, fname, debug): """generate the iddindex"""
astr = _readfname(fname) # fname is exhausted by the above read # reconstitute fname as a StringIO fname = StringIO(astr) # glist = iddgroups.iddtxt2grouplist(astr.decode('ISO-8859-2')) blocklst, commlst, commdct = extract_func(fname) name2refs = iddindex.makename2refdct(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 embedgroupdata(extract_func, fname, debug): """insert group info into extracted idd"""
astr = _readfname(fname) # fname is exhausted by the above read # reconstitute fname as a StringIO fname = StringIO(astr) try: astr = astr.decode('ISO-8859-2') except Exception as e: pass # for python 3 glist = iddgroups.iddtxt2grouplist(astr) blockl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractfields(data, commdct, objkey, fieldlists): """get all the objects of objkey. fieldlists will have a fieldlist for each of those objects. return the co...
# TODO : this assumes that the field list identical for # each instance of the object. This is not true. # So we should have a field list for each instance of the object # and map them with a zip objindex = data.dtls.index(objkey) objcomm = commdct[objindex] objfields = [] # get the fie...