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 remove(self): ''' a method to remove collection and all records in the collection :return: string with confirmation of deletion ''' title = '%s.remove' % self.__class__.__name__ # request bucket delete self.s3.delete_bucket(self.bucket_name) # return confirmation exit_msg = '%s collection has been removed from S3.' % self.bucket_name return exit_msg
<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_uris(self, base_uri, filter_list=None): """Return a set of internal URIs."""
return { re.sub(r'^/', base_uri, link.attrib['href']) for link in self.parsedpage.get_nodes_by_selector('a') if 'href' in link.attrib and ( link.attrib['href'].startswith(base_uri) or link.attrib['href'].startswith('/') ) and not is_uri_to_be_filtered(link.attrib['href'], filter_list) }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def TP0(dv, u): '''Demo problem 0 for horsetail matching, takes two input vectors of any size and returns a single output''' return np.linalg.norm(np.array(dv)) + np.linalg.norm(np.array(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 TP1(x, u, jac=False): '''Demo problem 1 for horsetail matching, takes two input vectors of size 2 and returns just the qoi if jac is False or the qoi and its gradient if jac is True''' factor = 0.1*(u[0]**2 + 2*u[0]*u[1] + u[1]**2) q = 0 + factor*(x[0]**2 + 2*x[1]*x[0] + x[1]**2) if not jac: return q else: grad = [factor*(2*x[0] + 2*x[1]), factor*(2*x[0] + 2*x[1])] return q, grad
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def TP2(dv, u, jac=False): '''Demo problem 2 for horsetail matching, takes two input vectors of size 2 and returns just the qoi if jac is False or the qoi and its gradient if jac is True''' y = dv[0]/2. z = dv[1]/2. + 12 q = 0.25*((y**2 + z**2)/10 + 5*u[0]*u[1] - z*u[1]**2) + 0.2*z*u[1]**3 + 7 if not jac: return q else: dqdx1 = (1./8.)*( 2*y/10. ) dqdx2 = (1./8.)*( 2*z/10. - u[1]**2) + 0.1*u[1]**3 return q, [dqdx1, dqdx2]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def TP3(x, u, jac=False): '''Demo problem 1 for horsetail matching, takes two input values of size 1''' q = 2 + 0.5*x + 1.5*(1-x)*u if not jac: return q else: grad = 0.5 -1.5*u return q, grad
<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, key, bucket): """ Get a cached item by key If the cached item isn't found the return None. """
try: return self._cache[bucket][key] except (KeyError, TypeError): 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 set(self, key, val, bucket): """ Set a cached item by key WARN: Regardless if the item is already in the cache, it will be udpated with the new value. """
if bucket not in self._cache: self._cache[bucket] = {} self._cache[bucket][key] = 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 create(self, project_name, template_name, substitutions): """ Launch the project creation. """
self.project_name = project_name self.template_name = template_name # create substitutions dictionary from user arguments # TODO: check what is given for subs in substitutions: current_sub = subs.split(',') current_key = current_sub[0].strip() current_val = current_sub[1].strip() self.substitutes_dict[current_key] = current_val self.term.print_info(u"Creating project '{0}' with template {1}" .format(self.term.text_in_color(project_name, TERM_PINK), template_name)) self.make_directories() self.make_files() self.make_posthook()
<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_directories(self): """ Create the directories of the template. """
# get the directories from the template directories = [] try: directories = self.directories() except AttributeError: self.term.print_info(u"No directory in the template.") working_dir = os.getcwd() # iteratively create the directories for directory in directories: dir_name = working_dir + '/' + directory if not os.path.isdir(dir_name): try: os.makedirs(dir_name) except OSError as error: if error.errno != errno.EEXIST: raise else: self.term.print_error_and_exit(u"The directory {0} already exists." .format(directory)) self.term.print_info(u"Creating directory '{0}'" .format(self.term.text_in_color(directory, TERM_GREEN)))
<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_files(self): """ Create the files of the template. """
# get the files from the template files = [] try: files = self.files() except AttributeError: self.term.print_info(u"No file in the template. Weird, but why not?") # get the substitutes intersecting the template and the cli try: for key in self.substitutes().keys(): if key not in self.substitutes_dict: self.substitutes_dict[key] = self.substitutes()[key] except AttributeError: self.term.print_info(u"No substitute in the template.") working_dir = os.getcwd() # iteratively create the files for directory, name, template_file in files: if directory: filepath = working_dir + '/' + directory + '/' + name filename = directory + '/' + name else: filepath = working_dir + '/' + name filename = name # open the file to write into try: output = open(filepath, 'w') except IOError: self.term.print_error_and_exit(u"Can't create destination"\ " file: {0}".format(filepath)) # open the template to read from if template_file: input_file = join(dirname(__file__), template_file + '.txt') # write each line of input file into output file, # templatized with substitutes try: with open(input_file, 'r') as line: template_line = Template(line.read()) try: output.write(template_line. safe_substitute(self.substitutes_dict).encode('utf-8')) except TypeError: output.write(template_line. safe_substitute(self.substitutes_dict)) output.close() except IOError: self.term.print_error_and_exit(u"Can't create template file"\ ": {0}".format(input_file)) else: output.close() # the file is empty, but still created self.term.print_info(u"Creating file '{0}'" .format(self.term.text_in_color(filename, TERM_YELLOW)))
<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_posthook(self): """ Run the post hook into the project directory. """
print(id(self.posthook), self.posthook) print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook) import ipdb;ipdb.set_trace() if self.posthook: os.chdir(self.project_name) # enter the project main directory self.posthook()
<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_in_file(self, file_path, old_exp, new_exp): """ In the given file, replace all 'old_exp' by 'new_exp'. """
self.term.print_info(u"Making replacement into {}" .format(self.term.text_in_color(file_path, TERM_GREEN))) # write the new version into a temporary file tmp_file = tempfile.NamedTemporaryFile(mode='w+t', delete=False) for filelineno, line in enumerate(io.open(file_path, encoding="utf-8")): if old_exp in line: line = line.replace(old_exp, new_exp) try: tmp_file.write(line.encode('utf-8')) except TypeError: tmp_file.write(line) name = tmp_file.name # keep the name tmp_file.close() shutil.copy(name, file_path) # replace the original one os.remove(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 add(self, si): '''puts `si` into the currently open chunk, which it creates if necessary. If this item causes the chunk to cross chunk_max, then the chunk closed after adding. ''' if self.o_chunk is None: if os.path.exists(self.t_path): os.remove(self.t_path) self.o_chunk = streamcorpus.Chunk(self.t_path, mode='wb') self.o_chunk.add(si) logger.debug('added %d-th item to chunk', len(self.o_chunk)) if len(self.o_chunk) == self.chunk_max: self.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 find_if(pred, iterable, default=None): """ Returns a reference to the first element in the ``iterable`` range for which ``pred`` returns ``True``. If no such element is found, the function returns ``default``. 3 :param pred: a predicate function to check a value from the iterable range :param iterable: an iterable range to check in :param default: a value that will be returned if no elements were found :returns: a reference to the first found element or default """
return next((i for i in iterable if pred(i)), default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_root(self, _, children): """The main node holding all the query. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: for ``WS`` (whitespace): ``None``. - 1: for ``NAMED_RESOURCE``: an instance of a subclass of ``.resources.Resource``. - 2: for ``WS`` (whitespace): ``None``. Returns ------- .resources.Resource An instance of a subclass of ``.resources.Resource``, with ``is_root`` set to ``True``. Example ------- <Field[foo] /> True <List[bar]> <Field[name] /> </List[bar]> True <Object[baz]> <Field[name] /> </Object[baz]> True """
resource = children[1] resource.is_root = True return resource
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_named_resource(self, _, children): """A resource in the query with its optional name. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: for ``OPTIONAL_RESOURCE_NAME``: str, the name of the resource, or ``None`` if not set in the query. - 1: for ``RESOURCE``: an instance of a subclass of ``.resources.Resource``. Returns ------- .resources.Resource An instance of a subclass of ``.resources.Resource``, with its ``name`` field set to the name in the query if set. Example ------- <Field[bar] /> <Field[foo] .bar /> <Field[foo] .bar /> """
name, resource = children if name: resource.name = name return resource
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_field(self, _, children): """A simple field. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: for ``FILTERS``: list of instances of ``.resources.Field``. Returns ------- .resources.Field An instance of ``.resources.Field`` with the correct name. Example ------- <Field[foo] /> <Field[foo] .foo(1) /> <Field[foo] .foo.bar() /> """
filters = children[0] return self.Field(getattr(filters[0], 'name', None), filters=filters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_named_object(self, _, children): """Manage an object, represented by a ``.resources.Object`` instance. This object is populated with data from the result of the ``FILTERS``. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: for ``FILTERS``: list of instances of ``.resources.Field``. - 1: for ``OBJECT``: an ``Object`` resource Example ------- <Object[foo]> <Field[name] /> </Object[foo]> """
filters, resource = children resource.name = filters[0].name resource.filters = filters return resource
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_named_list(self, _, children): """Manage a list, represented by a ``.resources.List`` instance. This list is populated with data from the result of the ``FILTERS``. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: for ``FILTERS``: list of instances of ``.resources.Field``. - 1: for ``LIST``: a ``List`` resource Example ------- <List[foo] .foo(1)> <Field[name] /> </List[foo]> """
filters, resource = children resource.name = filters[0].name resource.filters = filters return resource
<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_constants(): """Load physical constants to simulate the earth-sun system"""
# The universal gravitational constant # https://en.wikipedia.org/wiki/Gravitational_constant G: float = 6.67408E-11 # The names of the celestial bodies body_name = \ ['sun', 'moon', 'mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune'] # The mass of the celestial bodies # https://en.wikipedia.org/wiki/Earth_mass mass_earth: float = 5.9722E24 mass: Dict[str, float] = \ {'sun': mass_earth * 332946.0487, 'moon' : mass_earth * 0.012300037, 'mercury': mass_earth * 0.0553, 'venus': mass_earth * 0.815, 'earth': mass_earth * 1.0000, 'mars': mass_earth * 0.107, 'jupiter': mass_earth * 317.8, 'saturn': mass_earth * 95.2, 'uranus': mass_earth * 14.5, 'neptune': mass_earth * 17.1, } # The radii of the celestial bodiea # https://nineplanets.org/data1.html radius: Dict[str, float] = \ {'sun': 695000e3, 'moon': 1738e3, 'mercury': 2440e3, 'venus': 6052e3, 'earth': 6378e3, 'mars': 3397e3, 'jupiter': 71492e3, 'saturn': 60268e3, 'uranus': 35559e3, 'neptune': 24766e3 } return G, body_name, mass, radius
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def julian_day(t: date) -> int: """Convert a Python datetime to a Julian day"""
# Compute the number of days from January 1, 2000 to date t dt = t - julian_base_date # Add the julian base number to the number of days from the julian base date to date t return julian_base_number + dt.days
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_mse(q1, q2): """Compare the results of two simulations"""
# Difference in positions between two simulations dq = q2 - q1 # Mean squared error in AUs return np.sqrt(np.mean(dq*dq))/au2m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flux_v2(v_vars: List[fl.Var], i: int): """Make Fluxion with the speed squared of body i"""
# Index with the base of (v_x, v_y, v_z) for body i k = 3*i # The speed squared of body i return fl.square(v_vars[k+0]) + fl.square(v_vars[k+1]) + fl.square(v_vars[k+2])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def U_ij(q_vars: List[fl.Var], mass: np.ndarray, i: int, j: int): """Make Fluxion with the gratiational potential energy beween body i and j"""
# Check that the lengths are consistent assert len(q_vars) == 3 * len(mass) # Masses of the bodies i and j mi = mass[i] mj = mass[j] # Gravitational potential is -G * m1 * m2 / r U = -(G * mi * mj) / flux_r(q_vars, i, j) return 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 T_i(v_vars: List[fl.Var], mass: np.ndarray, i: int): """Make Fluxion with the kinetic energy of body i"""
# Check that the lengths are consistent assert len(v_vars) == 3 * len(mass) # Mass of the body i m = mass[i] # kineteic energy = 1/2 * mass * speed^2 T = (0.5 * m) * flux_v2(v_vars, i) return T
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_energy(time, H, T, U): """Plot kinetic and potential energy of system over time"""
# Normalize energy to initial KE T0 = T[0] H = H / T0 T = T / T0 U = U / T0 # Plot fig, ax = plt.subplots(figsize=[16,8]) ax.set_title('System Energy vs. Time') ax.set_xlabel('Time in Days') ax.set_ylabel('Energy (Ratio Initial KE)') ax.plot(time, T, label='T', color='r') ax.plot(time, U, label='U', color='b') ax.plot(time, H, label='H', color='k') ax.legend() ax.grid() plt.show()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_seq_records(self, seq_records): """Checks that SeqExpandedRecords are sorted by gene_code and then by voucher code. The dashes in taxon names need to be converted to underscores so the dataset will be accepted by Biopython to do format conversions. """
for seq_record in seq_records: seq_record.voucher_code = seq_record.voucher_code.replace("-", "_") unsorted_gene_codes = set([i.gene_code for i in seq_records]) sorted_gene_codes = list(unsorted_gene_codes) sorted_gene_codes.sort(key=lambda x: x.lower()) unsorted_voucher_codes = set([i.voucher_code for i in seq_records]) sorted_voucher_codes = list(unsorted_voucher_codes) sorted_voucher_codes.sort(key=lambda x: x.lower()) sorted_seq_records = [] for gene_code in sorted_gene_codes: for voucher_code in sorted_voucher_codes: for seq_record in seq_records: should_be_done = ( seq_record.gene_code == gene_code and seq_record.voucher_code == voucher_code ) if should_be_done: sorted_seq_records.append(seq_record) return sorted_seq_records
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _validate_outgroup(self, outgroup): """All voucher codes in our datasets have dashes converted to underscores."""
if outgroup: outgroup = outgroup.replace("-", "_") good_outgroup = False for seq_record in self.seq_records: if seq_record.voucher_code == outgroup: good_outgroup = True break if good_outgroup: self.outgroup = outgroup else: raise ValueError("The given outgroup {0!r} cannot be found in the " "input sequence records.".format(outgroup)) else: self.outgroup = 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 _prepare_data(self): """ Creates named tuple with info needed to create a dataset. :return: named tuple """
self._extract_genes() self._extract_total_number_of_chars() self._extract_number_of_taxa() self._extract_reading_frames() Data = namedtuple('Data', ['gene_codes', 'number_taxa', 'number_chars', 'seq_records', 'gene_codes_and_lengths', 'reading_frames']) self.data = Data(self.gene_codes, self.number_taxa, self.number_chars, self.seq_records, self._gene_codes_and_lengths, self.reading_frames)
<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_total_number_of_chars(self): """ sets `self.number_chars` to the number of characters as string. """
self._get_gene_codes_and_seq_lengths() sum = 0 for seq_length in self._gene_codes_and_lengths.values(): sum += sorted(seq_length, reverse=True)[0] self.number_chars = str(sum)
<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_number_of_taxa(self): """ sets `self.number_taxa` to the number of taxa as string """
n_taxa = dict() for i in self.seq_records: if i.gene_code not in n_taxa: n_taxa[i.gene_code] = 0 n_taxa[i.gene_code] += 1 number_taxa = sorted([i for i in n_taxa.values()], reverse=True)[0] self.number_taxa = str(number_taxa)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(self): """Read program parameters from command line and configuration files We support both command line arguments and configuration files. The command line arguments have always precedence over any configuration file parameters. This allows us to have most of our options in files but override them individually from the command line. """
# first we parse only for a configuration file with an initial parser init_parser = argparse.ArgumentParser( description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter, add_help = False) # we don't use a file metavar because we need to support both json/yml init_parser.add_argument("-c", "--config", action="store", help = "read from target configuration file") args, remaining_args = init_parser.parse_known_args() # read from supplied configuration file or try to find one in the # current working directory reader = None config_file = args.config or self.detect_config() if config_file: with open(config_file, 'r') as f: reader = ConfigReader(f.read()) # implement the rest cli options parser = argparse.ArgumentParser( parents = [init_parser], add_help = True, description = "Static wiki generator using Github's gists as pages") application_opts = reader.application if reader else {} default_options = self.merge_with_default_options(application_opts) parser.set_defaults(**default_options) parser.add_argument("-v", "--version", action="version", version="%(prog)s {0}".format(__version__)) parser.add_argument("-t", "--templates", action="store", help="read templates from specified folder") parser.add_argument("-o", "--output", action="store", help="generate static files in target folder") parser.add_argument("-u", "--baseurl", action="store", help="use a specific base URL instead of /") if reader: self.config = reader.config self.config['app'] = vars(parser.parse_args(remaining_args)) # parsing of command line argumenents is done check if we have gists if 'gists' not in self.config: raise WigikiConfigError("Cannot read gists. " "Check your configuration 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 detect_config(self): """check in the current working directory for configuration files"""
default_files = ("config.json", "config.yml") for file_ in default_files: if os.path.exists(file_): return 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 merge_with_default_options(self, config_opts): """merge options from configuration file with the default options"""
return dict(list(self.defaults.items()) + list(config_opts.items()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorize(): """Authorize to twitter. Use PIN authentification. :returns: Token for authentificate with Twitter. :rtype: :class:`autotweet.twitter.OAuthToken` """
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) url = auth.get_authorization_url() print('Open this url on your webbrowser: {0}'.format(url)) webbrowser.open(url) pin = input('Input verification number here: ').strip() token_key, token_secret = auth.get_access_token(verifier=pin) return OAuthToken(token_key, token_secret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand_url(status): """Expand url on statuses. :param status: A tweepy status to expand urls. :type status: :class:`tweepy.models.Status` :returns: A string with expanded urls. :rtype: :class:`str` """
try: txt = get_full_text(status) for url in status.entities['urls']: txt = txt.replace(url['url'], url['expanded_url']) except: # Manually replace txt = status tco_pattern = re.compile(r'https://t.co/\S+') urls = tco_pattern.findall(txt) for url in urls: with urlopen(url) as resp: expanded_url = resp.url txt = txt.replace(url, expanded_url) return 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 strip_tweet(text, remove_url=True): """Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :class:`str` :param remove_url: Remove urls. default :const:`True`. :type remove_url: :class:`boolean` :returns: Striped tweet message :rtype: :class:`str` """
if remove_url: text = url_pattern.sub('', text) else: text = expand_url(text) text = mention_pattern.sub('', text) text = html_parser.unescape(text) text = text.strip() return 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 read(fname): """Quick way to read a file content."""
content = None with open(os.path.join(here, fname)) as f: content = f.read() return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self): """ Download the archive from the IRS website. """
url = 'http://forms.irs.gov/app/pod/dataDownload/fullData' r = requests.get(url, stream=True) with open(self.zip_path, 'wb') as f: # This is a big file, so we download in chunks for chunk in r.iter_content(chunk_size=30720): logger.debug('Downloading...') f.write(chunk) f.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unzip(self): """ Unzip the archive. """
logger.info('Unzipping archive') with zipfile.ZipFile(self.zip_path, 'r') as zipped_archive: data_file = zipped_archive.namelist()[0] zipped_archive.extract(data_file, self.extract_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean(self): """ Get the .txt file from within the many-layered directory structure, then delete the directories. """
logger.info('Cleaning up archive') shutil.move( os.path.join( self.data_dir, 'var/IRS/data/scripts/pofd/download/FullDataFile.txt' ), self.final_path ) shutil.rmtree(os.path.join(self.data_dir, 'var')) os.remove(self.zip_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parse_and_errorlist(self): """Get the parselist and human-readable version, errorlist is returned, because it is used in error messages. """
d = self.__class__.__dict__ parselist = d.get('parselist') errorlist = d.get('errorlist') if parselist and not errorlist: errorlist = [] for t in parselist: if t[1] not in errorlist: errorlist.append(t[1]) errorlist = ' or '.join(errorlist) d['errorlist'] = errorlist return (parselist, errorlist)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. Encode all strings as UTF-8, which will be type 'str' not 'unicode' ''' if self.strip: text = text.strip() if self.pyclass is not None: return self.pyclass(text.encode(UNICODE_ENCODING)) return text.encode(UNICODE_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 set_prefix(self, elt, pyobj): '''use this method to set the prefix of the QName, method looks in DOM to find prefix or set new prefix. This method must be called before get_formatted_content. ''' if isinstance(pyobj, tuple): namespaceURI,localName = pyobj self.prefix = elt.getPrefix(namespaceURI)
<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(self, elt, ps, **kw): '''attempt to parse sequentially. No way to know ahead of time what this instance represents. Must be simple type so it can not have attributes nor children, so this isn't too bad. ''' self.setMemberTypeCodes() (nsuri,typeName) = self.checkname(elt, ps) #if (nsuri,typeName) not in self.memberTypes: # raise EvaluateException( # 'Union Type mismatch got (%s,%s) not in %s' % \ # (nsuri, typeName, self.memberTypes), ps.Backtrace(elt)) for indx in range(len(self.memberTypeCodes)): typecode = self.memberTypeCodes[indx] try: pyobj = typecode.parse(elt, ps) except ParseException, ex: continue except Exception, ex: continue if indx > 0: self.memberTypeCodes.remove(typecode) self.memberTypeCodes.insert(0, typecode) break else: raise return pyobj
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. items in list are space separated. ''' v = [] items = text.split() for item in items: v.append(self.itemTypeCode.text_to_data(item, elt, ps)) if self.pyclass is not None: return self.pyclass(v) return v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consumer(site, uri): """Consume URI using site config."""
config = load_site_config(site) model = _get_model('consume', config, uri) consumestore = get_consumestore( model=model, method=_config.get('storage', 'file'), bucket=_config.get('s3_data_bucket', None) ) consumestore.save_media() consumestore.save_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 crawler(site, uri=None): """Crawl URI using site config."""
config = load_site_config(site) model = _get_model('crawl', config, uri) visited_set, visited_uri_set, consume_set, crawl_set = get_site_sets( site, config ) if not visited_set.has(model.hash): visited_set.add(model.hash) visited_uri_set.add(model.uri) if ( model.is_consume_page and not consume_set.has(model.hash) ): consume_set.add(model.hash) consume_q.enqueue( consumer, site, model.uri ) else: for crawl_uri in model.uris_to_crawl: if ( not visited_uri_set.has(crawl_uri) and not crawl_set.has(crawl_uri) ): crawl_set.add(crawl_uri) crawl_q.enqueue( crawler, site, crawl_uri )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def killer(site): """Kill queues and Redis sets."""
config = load_site_config(site) crawl_q.empty() consume_q.empty() for site_set in get_site_sets(site, config): site_set.destroy()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GetAuth(self): '''Return a tuple containing client authentication data. ''' if self.auth: return self.auth for elt in self.ps.GetMyHeaderElements(): if elt.localName == 'BasicAuth' \ and elt.namespaceURI == ZSI_SCHEMA_URI: d = _auth_tc.parse(elt, self.ps) self.auth = (AUTH.zsibasic, d['Name'], d['Password']) return self.auth ba = self.environ.get('HTTP_AUTHENTICATION') if ba: ba = ba.split(' ') if len(ba) == 2 and ba[0].lower() == 'basic': ba = _b64_decode(ba[1]) self.auth = (AUTH.httpbasic,) + tuple(ba.split(':')) return self.auth self.auth = (AUTH.none,) return self.auth
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def permission_required_with_403(perm, login_url=None): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the login page or rendering a 403 as necessary. See :meth:`django.contrib.auth.decorators.permission_required`. """
return user_passes_test_with_403(lambda u: u.has_perm(perm), login_url=login_url)
<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_to_rgb(img): """ Convert an image to RGB if it isn't already RGB or grayscale """
if img.mode == 'CMYK' and HAS_PROFILE_TO_PROFILE: profile_dir = os.path.join(os.path.dirname(__file__), 'profiles') input_profile = os.path.join(profile_dir, "USWebUncoated.icc") output_profile = os.path.join(profile_dir, "sRGB_v4_ICC_preference.icc") return profileToProfile(img, input_profile, output_profile, outputMode='RGB') return img
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optimize(image, fmt='jpeg', quality=80): """ Optimize the image if the IMAGE_OPTIMIZATION_CMD is set. IMAGE_OPTIMIZATION_CMD must accept piped input """
from io import BytesIO if IMAGE_OPTIMIZATION_CMD and is_tool(IMAGE_OPTIMIZATION_CMD): image_buffer = BytesIO() image.save(image_buffer, format=fmt, quality=quality) image_buffer.seek(0) # If you don't reset the file pointer, the read command returns an empty string p1 = subprocess.Popen(IMAGE_OPTIMIZATION_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE) output_optim, output_err = p1.communicate(image_buffer.read()) if not output_optim: logger.debug("No image buffer received from IMAGE_OPTIMIZATION_CMD") logger.debug("output_err: {0}".format(output_err)) return image im = Image.open(BytesIO(output_optim)) return im else: return image
<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(filename, default=None): ''' Try to load @filename. If there is no loader for @filename's filetype, return @default. ''' ext = get_ext(filename) if ext in ldict: return ldict[ext](filename) else: return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def report(self, msg, do_reset=False, file=sys.stdout): """Print to stdout msg followed by the runtime. When true, do_reset will result in a reset of start time. """
print >> file, "%s (%s s)" % (msg, time.time() - self.start) if do_reset: self.start = time.time()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def result(self, msg, do_reset=False): """Return log message containing ellapsed time as a string. When true, do_reset will result in a reset of start time. """
result = "%s (%s s)" % (msg, time.time() - self.start) if do_reset: self.start = time.time() return 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 runtime(self): """Return ellapsed time and reset start. """
t = time.time() - self.start self.start = time.time() return t
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync_one(self, aws_syncr, amazon, gateway): """Make sure this gateway exists and has only attributes we want it to have"""
gateway_info = amazon.apigateway.gateway_info(gateway.name, gateway.location) if not gateway_info: amazon.apigateway.create_gateway(gateway.name, gateway.location, gateway.stages, gateway.resources, gateway.api_keys, gateway.domain_names) else: amazon.apigateway.modify_gateway(gateway_info, gateway.name, gateway.location, gateway.stages, gateway.resources, gateway.api_keys, gateway.domain_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 includeme(configurator): """ Add yaml configuration utilities. :param pyramid.config.Configurator configurator: pyramid's app configurator """
settings = configurator.registry.settings # lets default it to running path yaml_locations = settings.get('yaml.location', settings.get('yml.location', os.getcwd())) configurator.add_directive('config_defaults', config_defaults) configurator.config_defaults(yaml_locations) # reading yml configuration if configurator.registry['config']: config = configurator.registry['config'] log.debug('Yaml config created') # extend settings object if 'configurator' in config and config.configurator: _extend_settings(settings, config.configurator) # run include's if 'include' in config: _run_includemes(configurator, config.include) # let's calla a convenience request method configurator.add_request_method( lambda request: request.registry['config'], name='config', property=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 _translate_config_path(location): """ Translate location into fullpath according asset specification. Might be package:path for package related paths, or simply path :param str location: resource location :returns: fullpath :rtype: str """
# getting spec path package_name, filename = resolve_asset_spec(location.strip()) if not package_name: path = filename else: package = __import__(package_name) path = os.path.join(package_path(package), filename) return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _env_filenames(filenames, env): """ Extend filenames with ennv indication of environments. :param list filenames: list of strings indicating filenames :param str env: environment indicator :returns: list of filenames extended with environment version :rtype: list """
env_filenames = [] for filename in filenames: filename_parts = filename.split('.') filename_parts.insert(1, env) env_filenames.extend([filename, '.'.join(filename_parts)]) return env_filenames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extend_settings(settings, configurator_config, prefix=None): """ Extend settings dictionary with content of yaml's configurator key. .. note:: This methods changes multilayered subkeys defined within **configurator** into dotted keys in settings dictionary: .. code-block:: yaml configurator: sqlalchemy: url: mysql://user:password@host/dbname will result in **sqlalchemy.url**: mysql://user:password@host/dbname key value in settings dictionary. :param dict settings: settings dictionary :param dict configurator_config: yml defined settings :param str prefix: prefix for settings dict key """
for key in configurator_config: settings_key = '.'.join([prefix, key]) if prefix else key if hasattr(configurator_config[key], 'keys') and\ hasattr(configurator_config[key], '__getitem__'): _extend_settings( settings, configurator_config[key], prefix=settings_key ) else: settings[settings_key] = configurator_config[key]
<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_instance(uri): """Return an instance of Page."""
global _instances try: instance = _instances[uri] except KeyError: instance = Page( uri, client.get_instance() ) _instances[uri] = instance return instance
<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(self): """Fetch Page.content from client."""
self.content = self.client.get_content( uri=self.uri ) self.hash = hashlib.sha256( self.content ).hexdigest()
<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_objects(self, dirs=[], callwith={}): ''' Call this to load resources from each dir in @dirs. Code resources will receive @callwith as an argument. ''' for d in dirs: contents = ls(d) for t in contents: first = join(d, t) if t.startswith('.') or os.path.isfile(first): continue t_l = t.lower() for fl in ls(first): full = join(first, fl) if fl.startswith('.') or os.path.isdir(full): continue fl_n = fl.lower().rsplit('.', 1)[0] ty = guess_type(full) if ty == T_IMAGE: self.load_image(full, fl_n, t) elif ty == T_SOUND: self.load_sound(full, fl_n, t) elif ty == T_MUSIC: self.load_music(full, fl_n, t) elif ty == T_CODE and fl_n == '__init__': self.load_code(d, t, callwith) elif ty == T_PLAYLIST: self.load_playlist(full, fl_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 set_music(self, plylst, force=False): ''' Use to set the playlist to @plylst. If @force is False, the playlist will not be set if it is @plylst already. ''' plylst = plylst.lower() if plylst != self.cur_playlist or force: self.cur_playlist = plylst self.play_song(self.get_playlist().begin())
<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_m_vol(self, vol=None, relative=False): ''' Set the music volume. If @vol != None, It will be changed to it (or by it, if @relative is True.) ''' if vol != None: if relative: vol += self.m_vol self.m_vol = min(max(vol, 0), 1) pygame.mixer.music.set_volume(self.m_vol)
<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_s_vol(self, vol=None, relative=False): ''' Set the volume of all sounds. If @vol != None, It will be changed to it (or by it, if @relative is True.) ''' if vol != None: if relative: vol += self.s_vol self.s_vol = min(max(vol, 0), 1) for sgroup in self.sounds.values(): for snd in sgroup.values(): snd.set_volume()
<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_channel(self): ''' Used internally when playing sounds. ''' c = pygame.mixer.find_channel(not self.dynamic) while c is None: self.channels += 1 pygame.mixer.set_num_channels(self.channels) c = pygame.mixer.find_channel() return 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 event(self, utype, **kw): ''' Make a meta-event with a utype of @type. **@kw works the same as for pygame.event.Event(). ''' d = {'utype': utype} d.update(kw) pygame.event.post(pygame.event.Event(METAEVENT, d))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def loop(self, events=[]): ''' Run the loop. ''' try: for e in events: if e.type == METAEVENT: e = self.MetaEvent(e) for func in self.event_funcs.get(e.type, []): func(self, self.gstate, e) except self.Message as e: return e.message
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accumulate(a_generator, cooperator=None): """ Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the yielded contents of the generator function. """
if cooperator: own_cooperate = cooperator.cooperate else: own_cooperate = cooperate spigot = ValueBucket() items = stream_tap((spigot,), a_generator) d = own_cooperate(items).whenDone() d.addCallback(accumulation_handler, spigot) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_accumulate(max_batch_size, a_generator, cooperator=None): """ Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator which is iterated over in batches the size of max_batch_size. It should be more efficient to iterate over the generator in batches and still provide enough speed for non-blocking execution. :param max_batch_size: The number of iterations of the generator to consume at a time. :param a_generator: An iterator which yields some not None values. :return: A Deferred to which the next callback will be called with the yielded contents of the generator function. """
if cooperator: own_cooperate = cooperator.cooperate else: own_cooperate = cooperate spigot = ValueBucket() items = stream_tap((spigot,), a_generator) d = own_cooperate(i_batch(max_batch_size, items)).whenDone() d.addCallback(accumulation_handler, spigot) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_connection(): """Return a redis.Redis instance connected to REDIS_URL."""
# REDIS_URL is defined in .env and loaded into the environment by Honcho redis_url = os.getenv('REDIS_URL') # If it's not defined, use the Redis default if not redis_url: redis_url = 'redis://localhost:6379' urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) return redis.StrictRedis( host=url.hostname, port=url.port, db=0, password=url.password )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def work(): """Start an rq worker on the connection provided by create_connection."""
with rq.Connection(create_connection()): worker = rq.Worker(list(map(rq.Queue, listen))) worker.work()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _gen_shuffles(self): ''' Used internally to build a list for mapping between a random number and a song index. ''' # The current metasong index si = 0 # The shuffle mapper list self.shuffles = [] # Go through all our songs... for song in self.loop: # And add them to the list as many times as they say to. for i in range(song[1]): self.shuffles.append(si) si += 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 _new_song(self): ''' Used internally to get a metasong index. ''' # We'll need this later s = self.song if self.shuffle: # If shuffle is on, we need to (1) get a random song that # (2) accounts for weighting. This line does both. self.song = self.shuffles[random.randrange(len(self.shuffles))] else: # Nice and easy, just get the next song... self.song += 1 # But wait! need to make sure it exists! if self.song >= len(self.loop): # It doesn't, so start over at the beginning. self.song = 0 # Set flag if we have the same song as we had before. self.dif_song = s != self.song # Reset the position within the metasong self.pos = 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 _get_selectable(self): ''' Used internally to get a group of choosable tracks. ''' # Save some typing cursong = self.loop[self.song][0] if self.dif_song and len(cursong) > 1: # Position is relative to the intro of the track, # so we we will get the both the intro and body. s = cursong[0] + cursong[1] else: # Position is relative to the body of the track, so just get that. s = cursong[-1] # Return what we found return 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 _get_song(self): ''' Used internally to get the current track and make sure it exists. ''' # Try to get the current track from the start metasong if self.at_beginning: # Make sure it exists. if self.pos < len(self.start): # It exists, so return it. return self.start[self.pos] # It doesn't exist, so let's move on! self.at_beginning = False # Generate a new track selection self._new_track() # A bit more difficult than using the start metasong, # because we could have a beginning part. Call a function that gets all # applicable tracks from the metasong. s = self._get_selectable() # Make sure it is long enough while self.pos >= len(s): # Or pick a new metasong. self._new_song() # And repeat. s = self._get_selectable() # Found a track, return it. return s[self.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 begin(self): ''' Start over and get a track. ''' # Check for a start metasong if self.start: # We are in the beginning song self.at_beginning = True # And on the first track. self.pos = 0 else: # We aren't in the beginning song self.at_beginning = False # So we need to get new one. self._new_song() return self._get_song()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _applicationStart(self, data): """ Initializes the database connection pool. :param data: <object> event data object :return: <void> """
checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ "name" in self.application.config["viper.mysql"]: if len(self.application.config["viper.mysql"]["host"]) > 0 and \ self.application.config["viper.mysql"]["port"] > 0 and \ len(self.application.config["viper.mysql"]["name"]) > 0: checkup = True if checkup is not True: return try: self._connectionPool = adbapi.ConnectionPool( "MySQLdb", host=self.application.config["viper.mysql"]["host"], port=int(self.application.config["viper.mysql"]["port"]), user=self.application.config["viper.mysql"]["username"], passwd=self.application.config["viper.mysql"]["password"], db=self.application.config["viper.mysql"]["name"], charset=self.application.config["viper.mysql"]["charset"], cp_min=int( self.application.config["viper.mysql"]["connectionsMinimum"] ), cp_max=int( self.application.config["viper.mysql"]["connectionsMaximum"] ), cp_reconnect=True ) except Exception as e: self.log.error( "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) if "init" in self.application.config["viper.mysql"] \ and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: self._checkIfDatabaseIsEmpty( lambda isEmpty: self._scheduleDatabaseInit(isEmpty) , lambda error: self.log.error("[Viper.MySQL] Cannot check if database is empty. Error {error}", error=error) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): """ Check if database contains any tables. :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument is a boolean flag specifying if the database is empty or not :param failHandler: <function(<str>)> method called if interrogation failed where the first argument is the error message :return: <void> """
def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, successHandler): querySelect = \ "SELECT `TABLE_NAME` " \ "FROM INFORMATION_SCHEMA.TABLES " \ "WHERE " \ "`TABLE_SCHEMA` = %s" \ ";" try: transaction.execute( querySelect, (self.application.config["viper.mysql"]["name"],) ) tables = transaction.fetchall() except Exception as e: failCallback(e) return if successHandler is not None: reactor.callInThread(successHandler, len(tables) == 0) interaction = self.runInteraction(selectCallback, successHandler) interaction.addErrback(failCallback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _initDatabase(self): """ Initializes the database structure based on application configuration. :return: <void> """
queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) sqlFile.close() queries.extend(queriesInFile) def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() self.log.error( "[Viper.MySQL] _initDatabase() database error: {errorMessage}", errorMessage=errorMessage ) def runCallback(transaction, queries): try: for query in queries: transaction.execute(query) except Exception as e: failCallback(e) return interaction = self.runInteraction(runCallback, queries) interaction.addErrback(failCallback)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractFromSQLFile(self, filePointer, delimiter=";"): """ Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file pointer to SQL file :return: <list> list of queries """
data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\n": dataLinesIndex += 1 else: dataLines[dataLinesIndex] = "{}{}".format( dataLines[dataLinesIndex], c ) # forming SQL statements from all lines provided statements = [] statementsIndex = 0 for line in dataLines: # ignoring comments if line.startswith("--") or line.startswith("#"): continue # removing spaces line = line.strip() # ignoring blank lines if len(line) == 0: continue # appending each character to it's statement until delimiter is reached for c in line: if len(statements) - 1 < statementsIndex: statements.append("") statements[statementsIndex] = "{}{}".format( statements[statementsIndex], c ) if c == delimiter: statementsIndex += 1 return statements
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result. :param interaction: <function> method with first argument is a <adbapi.Transaction> instance :param args: additional positional arguments to be passed to interaction :param kwargs: keyword arguments to be passed to interaction :return: <defer> """
try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def runQuery(self, *args, **kwargs): """ Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute method :param kwargs: keyword arguments to be passed to cursor execute method :return: <defer> """
try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve(self, value, resource): """Solve a resource with a value. Arguments --------- value : ? A value to solve in combination with the given resource. The first filter of the resource will be applied on this value (next filters on the result of the previous filter). resource : dataql.resources.Resource An instance of a subclass of ``Resource`` to solve with the given value. Returns ------- (depends on the implementation of the ``coerce`` method) Raises ------ CannotSolve If a solver accepts to solve a resource but cannot finally solve it. Allows ``Registry.solve_resource`` to use the next available solver. Notes ----- This method simply calls ``solve_value``, then ``coerce`` with the result. To change the behavior, simply override at least one of these two methods. """
result = self.solve_value(value, resource) return self.coerce(result, resource)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve_value(self, value, resource): """Solve a resource with a value, without coercing. Arguments --------- value : ? A value to solve in combination with the given resource. The first filter of the resource will be applied on this value (next filters on the result of the previous filter). resource : dataql.resources.Resource An instance of a subclass of ``Resource`` to solve with the given value. Returns ------- The result of all filters applied on the value for the first filter, and result of the previous filter for next filters. Example ------- '2015-06-01' '2015-06-01' # Example of how to raise a ``CannotSolve`` exception. Traceback (most recent call last): """
# The given value is the starting point on which we apply the first filter. result = value # Apply filters one by one on the previous result. if result is not None: for filter_ in resource.filters: result = self.registry.solve_filter(result, filter_) if result is None: break return 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 can_solve(cls, resource): """Tells if the solver is able to resolve the given resource. Arguments --------- resource : subclass of ``dataql.resources.Resource`` The resource to check if it is solvable by the current solver class Returns ------- boolean ``True`` if the current solver class can solve the given resource, ``False`` otherwise. Example ------- (<class 'dataql.resources.Field'>,) True False """
for solvable_resource in cls.solvable_resources: if isinstance(resource, solvable_resource): return True 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 coerce(self, value, resource): """Coerce the value to an acceptable one. Only these kinds of values are returned as is: - str - int - float - True - False - None For all others values, it will be coerced using ``self.coerce_default`` (with convert the value to a string in the default implementation). Arguments --------- value : ? The value to be coerced. resource : dataql.resources.Resource The ``Resource`` object used to obtain this value from the original one. Returns ------- str | int | float | True | False | None The coerced value. Example ------- 'foo' 11 1.1 True False '2015-06-01' """
if value in (True, False, None): return value if isinstance(value, (int, float)): return value if isinstance(value, str): return value return self.coerce_default(value, resource)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coerce(self, value, resource): """Get a dict with attributes from ``value``. Arguments --------- value : ? The value to get some resources from. resource : dataql.resources.Object The ``Object`` object used to obtain this value from the original one. Returns ------- dict A dictionary containing the wanted resources for the given value. Key are the ``name`` attributes of the resources, and the values are the solved values. """
return {r.name: self.registry.solve_resource(value, r) for r in resource.resources}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coerce(self, value, resource): """Convert a list of objects in a list of dicts. Arguments --------- value : iterable The list (or other iterable) to get values to get some resources from. resource : dataql.resources.List The ``List`` object used to obtain this value from the original one. Returns ------- list A list with one entry for each iteration get from ``value``. If the ``resource`` has only one sub-resource, each entry in the result list will be the result for the subresource for each iteration. If the ``resource`` has more that one sub-resource, each entry in the result list will be another list with an entry for each subresource for the current iteration. Raises ------ dataql.solvers.exceptions.NotIterable When the value is not iterable. """
if not isinstance(value, Iterable): raise NotIterable(resource, self.registry[value]) # Case #1: we only have one sub-resource, so we return a list with this item for # each iteration if len(resource.resources) == 1: res = resource.resources[0] return [self.registry.solve_resource(v, res) for v in value] # Case #2: we have many sub-resources, we return a list with, for each iteration, a # list with all entries return [ [self.registry.solve_resource(v, res) for res in resource.resources] for v in value ]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_recordings_dictionary(list_selected, pronunciation_dictionary_filename, out_dictionary_filename, htk_trace, additional_dictionary_filenames=[]): """Create a pronunciation dictionary specific to a list of recordings"""
temp_words_fd, temp_words_file = tempfile.mkstemp() words = set() for recording in list_selected: words |= set([w.upper() for w in get_words_from_recording(recording)]) with codecs.open(temp_words_file, 'w', 'utf-8') as f: f.writelines([u'{}\n'.format(w) for w in sorted(list(words))]) prepare_dictionary(temp_words_file, pronunciation_dictionary_filename, out_dictionary_filename, htk_trace, global_script_filename=config.project_path('etc/global.ded'), additional_dictionary_filenames=additional_dictionary_filenames) os.remove(temp_words_file) 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 utf8_normalize(input_filename, comment_char='#', to_upper=False): """Normalize UTF-8 characters of a file """
# Prepare the input dictionary file in UTF-8 and NFC temp_dict_fd, output_filename = tempfile.mkstemp() logging.debug('to_nfc from file {} to file {}'.format(input_filename, output_filename)) with codecs.open(output_filename, 'w', 'utf-8') as f: with codecs.open(input_filename, 'r', 'utf-8') as input_f: lines = sorted([unicodedata.normalize(UTF8_NORMALIZATION, l) for l in input_f.readlines() if not l.strip().startswith(comment_char)]) if to_upper: lines = [l.upper() for l in lines] f.writelines(lines) return output_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 create_flat_start_model(feature_filename, state_stay_probabilities, symbol_list, output_model_directory, output_prototype_filename, htk_trace): """ Creates a flat start model by using HCompV to compute the global mean and variance. Then uses these global mean and variance to create an N-state model for each symbol in the given list. :param feature_filename: The filename containing the audio and feature file pairs :param output_model_directory: The directory where to write the created model :param output_prototype_filename: The prototype model filename :param htk_trace: Trace level for HTK :rtype : None """
# Create a prototype model create_prototype_model(feature_filename, output_prototype_filename, state_stay_probabilities=state_stay_probabilities) # Compute the global mean and variance config.htk_command("HCompV -A -D -T {} -f 0.01 " "-S {} -m -o {} -M {} {}".format(htk_trace, feature_filename, 'proto', output_model_directory, output_prototype_filename)) # Create an hmmdefs using the global mean and variance for all states and symbols # Duplicate the model 'proto' -> symbol_list proto_model_filename = config.path(output_model_directory, 'proto') model = htk.load_model(proto_model_filename) model = htk_model_utils.map_hmms(model, {'proto': symbol_list}) # vFloors -> macros vfloors_filename = config.path(output_model_directory, 'vFloors') variance_model = htk.load_model(vfloors_filename) model['macros'] += variance_model['macros'] macros, hmmdefs = htk_model_utils.split_model(model) htk.save_model(macros, config.path(output_model_directory, 'macros')) htk.save_model(hmmdefs, config.path(output_model_directory, 'hmmdefs'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recognise_model(feature_filename, symbollist_filename, model_directory, recognition_filename, pronunciation_dictionary_filename, list_words_filename='', cmllr_directory=None, tokens_count=None, hypotheses_count=1, htk_trace=0): """ Perform recognition using a model and assuming a single word language. If the list_words_filename is == '' then all the words in the dictionary are used as language words. """
# Normalize UTF-8 to avoid Mac problems temp_dictionary_filename = utf8_normalize(pronunciation_dictionary_filename) # Create language word list if list_words_filename: list_words = parse_wordlist(list_words_filename) else: list_words = sorted(parse_dictionary(temp_dictionary_filename).keys()) # Create language model temp_directory = config.project_path('tmp', create=True) grammar_filename = config.path(temp_directory, 'grammar_words') wdnet_filename = config.path(temp_directory, 'wdnet') logging.debug('Create language model') create_language_model(list_words, grammar_filename, wdnet_filename) # Handle the Adaptation parameters cmllr_arguments = '' if cmllr_directory: if not os.path.isdir(cmllr_directory): logging.error('CMLLR adapatation directory not found: {}'.format(cmllr_directory)) cmllr_arguments = "-J {} mllr2 -h '*/*_s%.mfc' -k -J {}".format( os.path.abspath(config.path(cmllr_directory, 'xforms')), os.path.abspath(config.path(cmllr_directory, 'classes'))) # Handle the N-Best parameters hypotheses_count = hypotheses_count or 1 tokens_count = tokens_count or int(math.ceil(hypotheses_count / 5.0)) if hypotheses_count == 1 and tokens_count == 1: nbest_arguments = "" else: nbest_arguments = "-n {tokens_count} {hypotheses_count} ".format(tokens_count=tokens_count, hypotheses_count=hypotheses_count) # Run the HTK command config.htk_command("HVite -A -l '*' -T {htk_trace} " "-H {model_directory}/macros -H {model_directory}/hmmdefs " "-i {recognition_filename} -S {feature_filename} " "{cmllr_arguments} -w {wdnet_filename} " "{nbest_arguments} " "-p 0.0 -s 5.0 " "{pronunciation_dictionary_filename} " "{symbollist_filename}".format(htk_trace=htk_trace, model_directory=model_directory, recognition_filename=recognition_filename, feature_filename=feature_filename, symbollist_filename=symbollist_filename, nbest_arguments=nbest_arguments, pronunciation_dictionary_filename=temp_dictionary_filename, wdnet_filename=wdnet_filename, cmllr_arguments=cmllr_arguments)) # Remove temporary files os.remove(temp_dictionary_filename) os.remove(wdnet_filename) os.remove(grammar_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 connect(self): """ Construct the psycopg2 connection instance :return: psycopg2.connect instance """
if self._conn: return self._conn self._conn = psycopg2.connect( self.config, cursor_factory=psycopg2.extras.RealDictCursor, ) self._conn.set_session(autocommit=True) psycopg2.extras.register_hstore(self._conn) return self._conn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pager(parser, token): """ Output pagination links. """
try: tag_name, page_obj = token.split_contents() except ValueError: raise template.TemplateSyntaxError('pager tag requires 1 argument (page_obj), %s given' % (len(token.split_contents()) - 1)) return PagerNode(page_obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def view_modifier(parser, token): """ Output view modifier. """
try: tag_name, view_modifier = token.split_contents() except ValueError: raise template.TemplateSyntaxError('view_modifier tag requires 1 argument (view_modifier), %s given' % (len(token.split_contents()) - 1)) return ViewModifierNode(view_modifier)