_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q57600
Aggie.run
train
def run(self): """ loops until exit command given """ while self.status != 'EXIT': print(self.process_input(self.get_input())) print('Bye')
python
{ "resource": "" }
q57601
Aggie.process_input
train
def process_input(self, question): """ takes a question and returns the best answer based on known skills """ ans = '' if self.status == 'EXIT': print('bye') sys.exit() if '?' in question: ans = self.info.find_answer(question) ...
python
{ "resource": "" }
q57602
show_data_file
train
def show_data_file(fname): """ shows a data file in CSV format - all files live in CORE folder """ txt = '<H2>' + fname + '</H2>' print (fname) #try: txt += web.read_csv_to_html_table(fname, 'Y') # it is ok to use a table for actual table data #except: # txt += '<H2>ERROR - cant read file</...
python
{ "resource": "" }
q57603
managed_process
train
def managed_process(process): """Wrapper for subprocess.Popen to work across various Python versions, when using the with syntax.""" try: yield process finally: for stream in [process.stdout, process.stdin, process.stderr]: if stream: stream.close() proces...
python
{ "resource": "" }
q57604
Bash.get_temporary_scripts_path
train
def get_temporary_scripts_path(self): """ Get path for temporary scripts. Returns: str: path for temporary scripts or None if not set """ result = None if len(self.config.temporary_scripts_path) > 0: if os.path.isdir(self.config.temporary_scripts_...
python
{ "resource": "" }
q57605
Bash.create_file_for
train
def create_file_for(self, script): """ Create a temporary, executable bash file. It also does render given script (string) with the model and the provided environment variables and optional also an item when using the B{with} field. Args: script (str): eithe...
python
{ "resource": "" }
q57606
Bash.render_bash_options
train
def render_bash_options(self): """Rendering Bash options.""" options = '' if self.config.debug: options += "set -x\n" if self.config.strict: options += "set -euo pipefail\n" return options
python
{ "resource": "" }
q57607
Bash.process_file
train
def process_file(self, filename): """Processing one file.""" if self.config.dry_run: if not self.config.internal: self.logger.info("Dry run mode for script %s", filename) with open(filename) as handle: for line in handle: yield ...
python
{ "resource": "" }
q57608
BaseSelector.unregister
train
def unregister(self, fileobj): """ Unregister a file object from being monitored. """ try: key = self._fd_to_key.pop(self._fileobj_lookup(fileobj)) except KeyError: raise KeyError("{0!r} is not registered".format(fileobj)) # Getting the fileno of a closed socket ...
python
{ "resource": "" }
q57609
Message.prepare
train
def prepare(self): """ does some basic validation """ try: assert(type(self.sender) is Channel) assert(type(self.receiver) is Channel) return True except: return False
python
{ "resource": "" }
q57610
Message.send
train
def send(self): """ this handles the message transmission """ #print('sending message to ' + self.receiver) if self.prepare(): ## TODO - send message via library print('sending message') lg.record_process('comms.py', 'Sending message ' + self.t...
python
{ "resource": "" }
q57611
buildIndex
train
def buildIndex(ipFile, ndxFile, append='Y', silent='N', useShortFileName='Y'): """ this creates an index of a text file specifically for use in AIKIF separates the ontology descriptions highest followed by values and lastly a final pass to get all delimited word parts. """ if silent == 'N': ...
python
{ "resource": "" }
q57612
format_op_row
train
def format_op_row(ipFile, totLines, totWords, uniqueWords): """ Format the output row with stats """ txt = os.path.basename(ipFile).ljust(36) + ' ' txt += str(totLines).rjust(7) + ' ' txt += str(totWords).rjust(7) + ' ' txt += str(len(uniqueWords)).rjust(7) + ' ' return txt
python
{ "resource": "" }
q57613
format_op_hdr
train
def format_op_hdr(): """ Build the header """ txt = 'Base Filename'.ljust(36) + ' ' txt += 'Lines'.rjust(7) + ' ' txt += 'Words'.rjust(7) + ' ' txt += 'Unique'.ljust(8) + '' return txt
python
{ "resource": "" }
q57614
AppendIndexDictionaryToFile
train
def AppendIndexDictionaryToFile(uniqueWords, ndxFile, ipFile, useShortFileName='Y'): """ Save the list of unique words to the master list """ if useShortFileName == 'Y': f = os.path.basename(ipFile) else: f = ipFile with open(ndxFile, "a", encoding='utf-8', errors='replace') as...
python
{ "resource": "" }
q57615
DisplayIndexAsDictionary
train
def DisplayIndexAsDictionary(word_occurrences): """ print the index as a dict """ word_keys = word_occurrences.keys() for num, word in enumerate(word_keys): line_nums = word_occurrences[word] print(word + " ") if num > 3: break
python
{ "resource": "" }
q57616
show
train
def show(title, lst, full=-1): """ for testing, simply shows a list details """ txt = title + ' (' + str(len(lst)) + ') items :\n ' num = 0 for i in lst: if full == -1 or num < full: if type(i) is str: txt = txt + i + ',\n ' else: t...
python
{ "resource": "" }
q57617
getWordList
train
def getWordList(ipFile, delim): """ extract a unique list of words and have line numbers that word appears """ indexedWords = {} totWords = 0 totLines = 0 with codecs.open(ipFile, "r",encoding='utf-8', errors='replace') as f: for line in f: totLines = totLines + 1 ...
python
{ "resource": "" }
q57618
multi_split
train
def multi_split(txt, delims): """ split by multiple delimiters """ res = [txt] for delimChar in delims: txt, res = res, [] for word in txt: if len(word) > 1: res += word.split(delimChar) return res
python
{ "resource": "" }
q57619
Script.creator
train
def creator(entry, config): """Preparing and creating script.""" script = render(config.script, model=config.model, env=config.env, item=config.item) temp = tempfile.NamedTemporaryFile(prefix="script-", suffix=".py", mode='w+t', delete=False) temp.writelines(script) temp.close()...
python
{ "resource": "" }
q57620
force_to_string
train
def force_to_string(unknown): """ converts and unknown type to string for display purposes. """ result = '' if type(unknown) is str: result = unknown if type(unknown) is int: result = str(unknown) if type(unknown) is float: result = str(unknown) if type(unkno...
python
{ "resource": "" }
q57621
Log.add_watch_point
train
def add_watch_point(self, string, rating, importance=5): """ For a log session you can add as many watch points which are used in the aggregation and extraction of key things that happen. Each watch point has a rating (up to you and can range from success to total failu...
python
{ "resource": "" }
q57622
Log.estimate_complexity
train
def estimate_complexity(self, x,y,z,n): """ calculates a rough guess of runtime based on product of parameters """ num_calculations = x * y * z * n run_time = num_calculations / 100000 # a 2014 PC does about 100k calcs in a second (guess based on prior logs) return sel...
python
{ "resource": "" }
q57623
Log.show_time_as_short_string
train
def show_time_as_short_string(self, seconds): """ converts seconds to a string in terms of seconds -> years to show complexity of algorithm """ if seconds < 60: return str(seconds) + ' seconds' elif seconds < 3600: return str(round(seconds/60, 1)...
python
{ "resource": "" }
q57624
Log._log
train
def _log(self, fname, txt, prg=''): """ logs an entry to fname along with standard date and user details """ if os.sep not in fname: fname = self.log_folder + os.sep + fname delim = ',' q = '"' dte = TodayAsString() usr = GetUserName() ...
python
{ "resource": "" }
q57625
Log.record_source
train
def record_source(self, src, prg=''): """ function to collect raw data from the web and hard drive Examples - new source file for ontologies, email contacts list, folder for xmas photos """ self._log(self.logFileSource , force_to_string(src), prg)
python
{ "resource": "" }
q57626
Log.record_command
train
def record_command(self, cmd, prg=''): """ record the command passed - this is usually the name of the program being run or task being run """ self._log(self.logFileCommand , force_to_string(cmd), prg)
python
{ "resource": "" }
q57627
Log.record_result
train
def record_result(self, res, prg=''): """ record the output of the command. Records the result, can have multiple results, so will need to work out a consistent way to aggregate this """ self._log(self.logFileResult , force_to_string(res), prg)
python
{ "resource": "" }
q57628
LogSummary.extract_logs
train
def extract_logs(self, fname, prg): """ read a logfile and return entries for a program """ op = [] with open(fname, 'r') as f: for line in f: if prg in line: op.append(line) return op
python
{ "resource": "" }
q57629
LogSummary.summarise_events
train
def summarise_events(self): """ takes the logfiles and produces an event summary matrix date command result process source 20140421 9 40 178 9 20140423 0 0 6 0 20140424 19 1 47 19 ...
python
{ "resource": "" }
q57630
LogSummary._count_by_date
train
def _count_by_date(self, fname, all_dates): """ reads a logfile and returns a dictionary by date showing the count of log entries """ if not os.path.isfile(fname): return {} d_log_sum = {} with open(fname, "r") as raw_log: for line in raw_l...
python
{ "resource": "" }
q57631
AgentMapDataFile.map_data
train
def map_data(self): """ provides a mapping from the CSV file to the aikif data structures. """ with open(self.src_file, "r") as f: for line in f: cols = line.split(',') print(cols)
python
{ "resource": "" }
q57632
variablename
train
def variablename(var): """ Returns the string of a variable name. """ s=[tpl[0] for tpl in itertools.ifilter(lambda x: var is x[1], globals().items())] s=s[0].upper() return s
python
{ "resource": "" }
q57633
BLASTquery
train
def BLASTquery(query,database,program,filter=None,\ format_type=None, expect=None,\ nucl_reward=None, nucl_penalty=None,\ gapcosts=None, matrix=None,\ hitlist_size=None, descriptions=None,\ alignments=None,\ ncbi_gi=None, threshol...
python
{ "resource": "" }
q57634
BLASTcheck
train
def BLASTcheck(rid,baseURL="http://blast.ncbi.nlm.nih.gov"): """ Checks the status of a query. :param rid: BLAST search request identifier. Allowed values: The Request ID (RID) returned when the search was submitted :param baseURL: server url. Default=http://blast.ncbi.nlm.nih.gov :returns status:...
python
{ "resource": "" }
q57635
BLASTresults
train
def BLASTresults(rid, format_type="Tabular", \ hitlist_size= None, alignments=None, \ ncbi_gi = None, format_object=None,\ baseURL="http://blast.ncbi.nlm.nih.gov"): """ Retrieves results for an RID. :param rid: BLAST search request identifier. Allowed valu...
python
{ "resource": "" }
q57636
generate_html
train
def generate_html(store): """ Generating HTML report. Args: store (Store): report data. Returns: str: rendered HTML template. """ spline = { 'version': VERSION, 'url': 'https://github.com/Nachtfeuer/pipeline', 'generated': datetime.now().strftime("%A, %d...
python
{ "resource": "" }
q57637
TokensCompressor.__begin_of_list
train
def __begin_of_list(self, ast_token): """Handle begin of a list.""" self.list_level += 1 if self.list_level == 1: self.final_ast_tokens.append(ast_token)
python
{ "resource": "" }
q57638
TokensCompressor.__end_of_list
train
def __end_of_list(self, ast_token): """Handle end of a list.""" self.list_level -= 1 if self.list_level == 0: if self.list_entry is not None: self.final_ast_tokens.append(self.list_entry) self.list_entry = None self.final_ast_tokens.append(...
python
{ "resource": "" }
q57639
TokensCompressor.__default
train
def __default(self, ast_token): """Handle tokens inside the list or outside the list.""" if self.list_level == 1: if self.list_entry is None: self.list_entry = ast_token elif not isinstance(ast_token, type(self.list_entry)): self.final_ast_tokens.a...
python
{ "resource": "" }
q57640
TokensCompressor.compress
train
def compress(self): """Main function of compression.""" for ast_token in self.ast_tokens: if type(ast_token) in self.dispatcher: # pylint: disable=unidiomatic-typecheck self.dispatcher[type(ast_token)](ast_token) else: self.dispatcher['default'](a...
python
{ "resource": "" }
q57641
Condition.get_tokens
train
def get_tokens(condition): """ Get AST tokens for Python condition. Returns: list: list of AST tokens """ try: ast_tokens = list(ast.walk(ast.parse(condition.strip()))) except SyntaxError as exception: Logger.get_logger(__name__).error...
python
{ "resource": "" }
q57642
Condition.match_tokens
train
def match_tokens(ast_tokens, ast_types): """ Verify that each token in order does match the expected types. The list provided by `get_tokens` does have three more elements at the beginning of the list which should be always the same for a condition (Module and Expr). Those are a...
python
{ "resource": "" }
q57643
Condition.find_rule
train
def find_rule(condition): """ Find rule for given condition. Args: condition (str): Python condition as string. Returns: str, list, function: found rule name, list of AST tokens for condition and verification function. ""...
python
{ "resource": "" }
q57644
Condition.evaluate
train
def evaluate(condition): """ Evaluate simple condition. >>> Condition.evaluate(' 2 == 2 ') True >>> Condition.evaluate(' not 2 == 2 ') False >>> Condition.evaluate(' not "abc" == "xyz" ') True >>> Condition.evaluate('2 in [2, 4, 6, 8...
python
{ "resource": "" }
q57645
start_aikif
train
def start_aikif(): """ starts the web interface and possibly other processes """ if sys.platform[0:3] == 'win': os.system("start go_web_aikif.bat") else: os.system("../aikif/web_app/web_aikif.py") import webbrowser import time time.sleep(1) webbrowser...
python
{ "resource": "" }
q57646
get_creator_by_name
train
def get_creator_by_name(name): """ Get creator function by name. Args: name (str): name of the creator function. Returns: function: creater function. """ return {'docker(container)': Container.creator, 'shell': Bash.creator, 'docker(image)': Image.creator, ...
python
{ "resource": "" }
q57647
worker
train
def worker(data): """Running on shell via multiprocessing.""" creator = get_creator_by_name(data['creator']) shell = creator(data['entry'], ShellConfig(script=data['entry']['script'], title=data['entry']['title'] if 'title' in data['entry'] else '', ...
python
{ "resource": "" }
q57648
Tasks.get_merged_env
train
def get_merged_env(self, include_os=False): """ Copying and merging environment variables. Args: include_os (bool): when true then include the environment variables (default: False) Returns: dict: environment variables as defined in the pipeline ...
python
{ "resource": "" }
q57649
Tasks.prepare_shell_data
train
def prepare_shell_data(self, shells, key, entry): """Prepare one shell or docker task.""" if self.can_process_shell(entry): if key in ['python']: entry['type'] = key if 'with' in entry and isinstance(entry['with'], str): rendered_with = ast.litera...
python
{ "resource": "" }
q57650
Tasks.process
train
def process(self, document): """Processing a group of tasks.""" self.logger.info("Processing group of tasks (parallel=%s)", self.get_parallel_mode()) self.pipeline.data.env_list[2] = {} output, shells = [], [] result = Adapter({'success': True, 'output': []}) for task_en...
python
{ "resource": "" }
q57651
Tasks.process_shells_parallel
train
def process_shells_parallel(self, shells): """Processing a list of shells parallel.""" output = [] success = True with closing(multiprocessing.Pool(multiprocessing.cpu_count())) as pool: for result in [Adapter(entry) for entry in pool.map(worker, [shell for shell in shells])]...
python
{ "resource": "" }
q57652
Tasks.process_shells_ordered
train
def process_shells_ordered(self, shells): """Processing a list of shells one after the other.""" output = [] for shell in shells: entry = shell['entry'] config = ShellConfig(script=entry['script'], title=entry['title'] if 'title' in entry else '', ...
python
{ "resource": "" }
q57653
Tasks.process_shells
train
def process_shells(self, shells): """Processing a list of shells.""" result = {'success': True, 'output': []} if self.parallel and len(shells) > 1: result = self.process_shells_parallel(shells) elif len(shells) > 0: result = self.process_shells_ordered(shells) ...
python
{ "resource": "" }
q57654
Tasks.process_shell
train
def process_shell(self, creator, entry, config): """Processing a shell entry.""" self.logger.info("Processing Bash code: start") output = [] shell = creator(entry, config) for line in shell.process(): output.append(line) self.logger.info(" | %s", line) ...
python
{ "resource": "" }
q57655
Tasks.run_cleanup
train
def run_cleanup(self, env, exit_code): """Run cleanup hook when configured.""" output = [] if self.pipeline.data.hooks and len(self.pipeline.data.hooks.cleanup) > 0: env.update({'PIPELINE_RESULT': 'FAILURE'}) env.update({'PIPELINE_SHELL_EXIT_CODE': str(exit_code)}) ...
python
{ "resource": "" }
q57656
Tasks.__handle_variable
train
def __handle_variable(self, shell_entry, output): """ Saving output for configured variable name. Args: shell_entry(dict): shell based configuration (shell, docker container or Python). output: list of strings representing output of last shell """ if 'var...
python
{ "resource": "" }
q57657
main
train
def main(): """ This is the main body of the process that does the work. Summary: - load the raw data - read in rules list - create log events for AIKIF according to rules [map] - create new facts / reports based on rules [report] OUTPUT = AIKIF mapping : Date_of_...
python
{ "resource": "" }
q57658
BaseAPIParameters._clean_params
train
def _clean_params(self, params): """Removes parameters whose values are set to None. """ clean_params = {} for key, value in params.iteritems(): if value is not None: clean_params[key] = value return clean_params
python
{ "resource": "" }
q57659
Catchment.distance_to
train
def distance_to(self, other_catchment): """ Returns the distance between the centroids of two catchments in kilometers. :param other_catchment: Catchment to calculate distance to :type other_catchment: :class:`.Catchment` :return: Distance between the catchments in km. :...
python
{ "resource": "" }
q57660
Descriptors.urbext
train
def urbext(self, year): """ Estimate the `urbext2000` parameter for a given year assuming a nation-wide urbanisation curve. Methodology source: eqn 5.5, report FD1919/TR :param year: Year to provide estimate for :type year: float :return: Urban extent parameter ...
python
{ "resource": "" }
q57661
PotDataset.continuous_periods
train
def continuous_periods(self): """ Return a list of continuous data periods by removing the data gaps from the overall record. """ result = [] # For the first period start_date = self.start_date for gap in self.pot_data_gaps: end_date = gap.start_date ...
python
{ "resource": "" }
q57662
InMemoryFiles.add_path
train
def add_path(self, path, path_filter=None): """ Adding all files from given path to the object. Args: path (str): valid, existing directory """ for root, _, files in os.walk(path): for filename in files: full_path_and_filename = os.path.jo...
python
{ "resource": "" }
q57663
InMemoryFiles.from_json
train
def from_json(data): """ Convert JSON into a in memory file storage. Args: data (str): valid JSON with path and filenames and the base64 encoding of the file content. Returns: InMemoryFiles: in memory file storage """ memf...
python
{ "resource": "" }
q57664
delete_file
train
def delete_file(f, ignore_errors=False): """ delete a single file """ try: os.remove(f) except Exception as ex: if ignore_errors: return print('ERROR deleting file ' + str(ex))
python
{ "resource": "" }
q57665
delete_files_in_folder
train
def delete_files_in_folder(fldr): """ delete all files in folder 'fldr' """ fl = glob.glob(fldr + os.sep + '*.*') for f in fl: delete_file(f, True)
python
{ "resource": "" }
q57666
copy_file
train
def copy_file(src, dest): """ copy single file """ try: shutil.copy2(src , dest) except Exception as ex: print('ERROR copying file' + str(ex))
python
{ "resource": "" }
q57667
copy_files_to_folder
train
def copy_files_to_folder(src, dest, xtn='*.txt'): """ copies all the files from src to dest folder """ try: all_files = glob.glob(os.path.join(src,xtn)) for f in all_files: copy_file(f, dest) except Exception as ex: print('ERROR copy_files_to_folder - ' + str(ex))
python
{ "resource": "" }
q57668
main
train
def main(): """ script to setup folder structures for AIKIF and prepare data tables. """ print('\n\n /------- AIKIF Installation --------\\') print(' | s. show current setup |') print(' | f. setup folder structures |') print(' | c. create sample data |') ...
python
{ "resource": "" }
q57669
load_graph_from_rdf
train
def load_graph_from_rdf(fname): """ reads an RDF file into a graph """ print("reading RDF from " + fname + "....") store = Graph() store.parse(fname, format="n3") print("Loaded " + str(len(store)) + " tuples") return store
python
{ "resource": "" }
q57670
show_graph_summary
train
def show_graph_summary(g): """ display sample data from a graph """ sample_data = [] print("list(g[RDFS.Class]) = " + str(len(list(g[RDFS.Class])))) # Get Subject Lists num_subj = 0 for subj in g.subjects(RDF.type): num_subj += 1 if num_subj < 5: sample_data.append("s...
python
{ "resource": "" }
q57671
export
train
def export(g, csv_fname): """ export a graph to CSV for simpler viewing """ with open(csv_fname, "w") as f: num_tuples = 0 f.write('"num","subject","predicate","object"\n') for subj, pred, obj in g: num_tuples += 1 f.write('"' + str(num_tuples) + '",') ...
python
{ "resource": "" }
q57672
get_string_from_rdf
train
def get_string_from_rdf(src): """ extracts the real content from an RDF info object """ res = src.split("/") #[:-1] return "".join([l.replace('"', '""') for l in res[len(res) - 1]])
python
{ "resource": "" }
q57673
create_sample_file
train
def create_sample_file(ip, op, num_lines): """ make a short version of an RDF file """ with open(ip, "rb") as f: with open(op, "wb") as fout: for _ in range(num_lines): fout.write(f.readline() )
python
{ "resource": "" }
q57674
Select.flatten
train
def flatten(*sequence): """Flatten nested sequences into one.""" result = [] for entry in sequence: if isinstance(entry, list): result += Select.flatten(*entry) elif isinstance(entry, tuple): result += Select.flatten(*entry) els...
python
{ "resource": "" }
q57675
Select.build
train
def build(self): """Do the query.""" result = [] for entry in self.sequence: ignore = False for filter_function in self.filter_functions: if not filter_function(entry): ignore = True break if not ignore: ...
python
{ "resource": "" }
q57676
extract_all
train
def extract_all(zipfile, dest_folder): """ reads the zip file, determines compression and unzips recursively until source files are extracted """ z = ZipFile(zipfile) print(z) z.extract(dest_folder)
python
{ "resource": "" }
q57677
create_zip_from_file
train
def create_zip_from_file(zip_file, fname): """ add a file to the archive """ with zipfile.ZipFile(zip_file, 'w') as myzip: myzip.write(fname)
python
{ "resource": "" }
q57678
create_zip_from_folder
train
def create_zip_from_folder(zip_file, fldr, mode="r"): """ add all the files from the folder fldr to the archive """ #print('zip from folder - adding folder : ', fldr) zipf = zipfile.ZipFile(zip_file, 'w') for root, dirs, files in os.walk(fldr): for file in files: fullname...
python
{ "resource": "" }
q57679
AioWeakMethodContainer.add_method
train
def add_method(self, loop, callback): """Add a coroutine function Args: loop: The :class:`event loop <asyncio.BaseEventLoop>` instance on which to schedule callbacks callback: The :term:`coroutine function` to add """ f, obj = get_method_vars(call...
python
{ "resource": "" }
q57680
AioWeakMethodContainer.iter_methods
train
def iter_methods(self): """Iterate over stored coroutine functions Yields: Stored :term:`coroutine function` objects .. seealso:: :meth:`pydispatch.utils.WeakMethodContainer.iter_instances` """ for wrkey, obj in self.iter_instances(): f, obj_id = wrkey ...
python
{ "resource": "" }
q57681
AioWeakMethodContainer.submit_coroutine
train
def submit_coroutine(self, coro, loop): """Schedule and await a coroutine on the specified loop The coroutine is wrapped and scheduled using :func:`asyncio.run_coroutine_threadsafe`. While the coroutine is "awaited", the result is not available as method returns immediately. Ar...
python
{ "resource": "" }
q57682
File.launch
train
def launch(self): """ launch a file - used for starting html pages """ #os.system(self.fullname) # gives permission denied seeing it needs to be chmod +x import subprocess try: retcode = subprocess.call(self.fullname, shell=True) if retcode < 0: pr...
python
{ "resource": "" }
q57683
File.delete
train
def delete(self): """ delete a file, don't really care if it doesn't exist """ if self.fullname != "": try: os.remove(self.fullname) except IOError: print("Cant delete ",self.fullname)
python
{ "resource": "" }
q57684
TextFile.count_lines_in_file
train
def count_lines_in_file(self, fname=''): """ you wont believe what this method does """ i = 0 if fname == '': fname = self.fullname try: #with open(fname, encoding="utf8") as f: with codecs.open(fname, "r",encoding='utf8', errors='ignore') as f: ...
python
{ "resource": "" }
q57685
TextFile.count_lines_of_code
train
def count_lines_of_code(self, fname=''): """ counts non blank lines """ if fname == '': fname = self.fullname loc = 0 try: with open(fname) as f: for l in f: if l.strip() != '': loc += 1 r...
python
{ "resource": "" }
q57686
TextFile.get_file_sample
train
def get_file_sample(self, numLines=10): """ retrieve a sample of the file """ res = '' try: with open(self.fullname, 'r') as f: for line_num, line in enumerate(f): res += str(line_num).zfill(5) + ' ' + line if line_num >= numLi...
python
{ "resource": "" }
q57687
TextFile.append_text
train
def append_text(self, txt): """ adds a line of text to a file """ with open(self.fullname, "a") as myfile: myfile.write(txt)
python
{ "resource": "" }
q57688
TextFile.load_file_to_string
train
def load_file_to_string(self): """ load a file to a string """ try: with open(self.fullname, 'r') as f: txt = f.read() return txt except IOError: return ''
python
{ "resource": "" }
q57689
TextFile.load_file_to_list
train
def load_file_to_list(self): """ load a file to a list """ lst = [] try: with open(self.fullname, 'r') as f: for line in f: lst.append(line) return lst except IOError: return lst
python
{ "resource": "" }
q57690
get_program_list
train
def get_program_list(): """ get a HTML formatted view of all Python programs in all subfolders of AIKIF, including imports and lists of functions and classes """ colList = ['FileName','FileSize','Functions', 'Imports'] txt = '<TABLE width=90% border=0>' txt += format_file_table_header(c...
python
{ "resource": "" }
q57691
get_subfolder
train
def get_subfolder(txt): """ extracts a displayable subfolder name from full filename """ root_folder = os.sep + 'aikif' + os.sep ndx = txt.find(root_folder, 1) return txt[ndx:].replace('__init__.py', '')
python
{ "resource": "" }
q57692
get_functions
train
def get_functions(fname): """ get a list of functions from a Python program """ txt = '' with open(fname, 'r') as f: for line in f: if line.strip()[0:4] == 'def ': txt += '<PRE>' + strip_text_after_string(strip_text_after_string(line, '#')[4:], ':') + '</PRE>\n' ...
python
{ "resource": "" }
q57693
strip_text_after_string
train
def strip_text_after_string(txt, junk): """ used to strip any poorly documented comments at the end of function defs """ if junk in txt: return txt[:txt.find(junk)] else: return txt
python
{ "resource": "" }
q57694
get_imports
train
def get_imports(fname): """ get a list of imports from a Python program """ txt = '' with open(fname, 'r') as f: for line in f: if line[0:6] == 'import': txt += '<PRE>' + strip_text_after_string(line[7:], ' as ') + '</PRE>\n' return txt + '<BR>'
python
{ "resource": "" }
q57695
main
train
def main(arg1=55, arg2='test', arg3=None): """ This is a sample program to show how a learning agent can be logged using AIKIF. The idea is that this main function is your algorithm, which will run until it finds a successful result. The result is returned and the time taken is logged. ...
python
{ "resource": "" }
q57696
redis_server.get
train
def get(self, key): """ get a set of keys from redis """ res = self.connection.get(key) print(res) return res
python
{ "resource": "" }
q57697
Packer.creator
train
def creator(_, config): """Creator function for creating an instance of a Packer image script.""" packer_script = render(config.script, model=config.model, env=config.env, variables=config.variables, item=config.item) filename = "packer.dry.run.see.comment" ...
python
{ "resource": "" }
q57698
process_jpeg_bytes
train
def process_jpeg_bytes(bytes_in, quality=DEFAULT_JPEG_QUALITY): """Generates an optimized JPEG from JPEG-encoded bytes. :param bytes_in: the input image's bytes :param quality: the output JPEG quality (default 95) :returns: Optimized JPEG bytes :rtype: bytes :raises ValueError: Guetzli was no...
python
{ "resource": "" }
q57699
process_rgb_bytes
train
def process_rgb_bytes(bytes_in, width, height, quality=DEFAULT_JPEG_QUALITY): """Generates an optimized JPEG from RGB bytes. :param bytes bytes_in: the input image's bytes :param int width: the width of the input image :param int height: the height of the input image :param int quality: the output ...
python
{ "resource": "" }