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 saveform(cls, form): """ Create and save form model data to database """
columns = dict() for name, field in cls.form_fields.iteritems(): columns[name] = getattr(form, field).data instance = cls(**columns) return instance.save()
<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_by_id(cls, id): """ Get model by identifier """
if any((isinstance(id, basestring) and id.isdigit(), isinstance(id, (int, float)))): return cls.query.get(int(id)) 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 update(self, commit=True, **kwargs): """ Update model attributes and save to database """
for (attr, value) in kwargs.iteritems(): setattr(self, attr, value) return commit and self.save() or self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, commit=True): """ Save model to database """
db.session.add(self) if commit: db.session.commit() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, commit=True): """ Delete model from database """
db.session.delete(self) return commit and db.session.commit()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def verify_dir_structure(full_path): '''Check if given directory to see if it is usable by s2. Checks that all required directories exist under the given directory, and also checks that they are writable. ''' if full_path == None: return False r = True for d2c in PREDEFINED_DIR_NAMES: #if d2c == "s2": # d2c = ".s2" cp2c = os.path.join(full_path, d2c) #complete path to check if not os.path.isdir(cp2c): r = False break else: #exists, let's check it's writable if not os.access(cp2c, os.W_OK): r = False break return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dir_param_valid(d): '''True if d is a string and it's an existing directory.''' r = True if not isinstance(d, str) : r = False raise TypeError if not os.path.isdir(d): r = False raise ValueError return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dir_empty(d): '''Return True if given directory is empty, false otherwise.''' flist = glob.glob(os.path.join(d,'*')) return (len(flist) == 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 is_base_dir(d): '''True if the dir is valid and it contains a dir called s2''' if not dir_param_valid(d): # pragma: no cover raise else: mfn = os.path.join(d,'s2') #marker name. it must be a directory. return os.path.isdir(mfn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def discover_base_dir(start_dir): '''Return start_dir or the parent dir that has the s2 marker. Starting from the specified directory, and going up the parent chain, check each directory to see if it's a base_dir (contains the "marker" directory *s2*) and return it. Otherwise, return the start_dir. ''' if is_base_dir(start_dir): return start_dir pcl = start_dir.split('/') #path component list found_base_dir = None for i in range(1, len(pcl)+1): d2c = '/'.join(pcl[:-i]) if (d2c == ''): d2c = '/' if is_base_dir(d2c): found_base_dir = d2c break return found_base_dir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def package_data_location(): '''Get the locations of themes distributed with this package. Just finds if there are templates, and returns a dictionary with the corresponding values. ''' pkg_dir = os.path.split(__file__)[0] pkg_data_dir = os.path.join(pkg_dir,'data') return pkg_data_dir
<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_directories(self): '''Initialize variables based on evidence about the directories.''' if self._dirs['initial'] == None: self._dirs['base'] = discover_base_dir(self._dirs['run']) else: self._dirs['base'] = discover_base_dir(self._dirs['initial']) # now, if 'base' is None (no base directory was found) then the only # allowed operation is init self._update_dirs_on_base() # we might have set the directory variables fine, but the tree # might not exist yet. _tree_ready is a flag for that. self._tree_ready = verify_dir_structure(self._dirs['base']) if self._tree_ready: self._read_site_config()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _update_dirs_on_base(self): '''Fill up the names of dirs based on the contents of 'base'.''' if self._dirs['base'] != None: for d in self._predefined_dir_names: dstr = d #if d == "s2": # dstr = '.'+d self._dirs[d] = os.path.join(self._dirs['base'], dstr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def init_structure(self): '''Initialize a directory to serve as a Simply Static site. Initialization is done on the base_dir (base_dir is set upon __init__, so it has a value when this method is called), and it is only performed if base_dir is empty and it is writeable. This operation creates the directories, copies any existing templates to the source_dir and common_dir, and creates the default configuration file within the directory s2 ''' if self._dirs['base'] != None: # pragma: no cover #there's a base here or up the chain raise ValueError #cannot initialize else: if self._dirs['initial'] != None: # pragma: no cover self._dirs['base'] = self._dirs['initial'] else: # pragma: no cover self._dirs['base'] = self._dirs['run'] #now proceed self._update_dirs_on_base() if (not dir_empty(self._dirs['base']) ) or \ (not os.access(self._dirs['base'], os.W_OK)): raise ValueError # copy the dirs from package data to the base dir (common,themes) pdl = package_data_location() datadirs = glob.glob(os.path.join(pdl,"*")) for dd in datadirs: if os.path.isdir(dd): shutil.copytree(dd, os.path.join(self._dirs['base'], os.path.split(dd)[1])) # create all predefined dirs that don't exist yet in base for d in self._dirs: if not d in ['initial', 'run', 'base']: if not os.path.isdir(self._dirs[d]): os.mkdir(self._dirs[d]) self._tree_ready = verify_dir_structure(self._dirs['base']) self.site_config = self._create_default_config()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def random_page(self, title=None, content=None, creation_date=None, tags=None): '''Generate random page, write it and return the corresponding \ object.''' if title == None: title = util.random_title() if content == None: content = util.random_md_page() if creation_date == None: creation_date = util.random_date() if tags == None: tags = [] # yes, we pass self as a param. It's a ref to this site, that # is needed by the page p = s2page.Page(self, title) #here, set date and tags?? # date = util.random_date() p.content = content p.creation_date = creation_date p.tags = tags p.write() return p
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def page_exists_on_disk(self, slug): '''Return true if post directory and post file both exist.''' r = False page_dir = os.path.join(self.dirs['source'], slug) page_file_name = os.path.join(page_dir, slug + '.md') if os.path.isdir(page_dir): if os.path.isfile(page_file_name): r = True return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rename_page(self, old_slug, new_title): '''Load the page corresponding to the slug, and rename it.''' #load page p = s2page.Page(self, old_slug, isslug=True) p.rename(new_title)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _wipe_www_page(self, slug): '''Remove all data in www about the page identified by slug.''' wd = os.path.join(self._dirs['www'], slug) if os.path.isdir(wd): # pragma: no cover shutil.rmtree(wd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _pages_to_generate(self): '''Return list of slugs that correspond to pages to generate.''' # right now it gets all the files. In theory, It should only # get what's changed... but the program is not doing that yet. all_pages = self.get_page_names() # keep only those whose status is published ptg = [] for slug in all_pages: p = s2page.Page(self, slug, isslug=True) if p.published: ptg.append({'slug': p.slug, 'title':p.title, 'date': p.creation_date }) # sort the ptg array in reverse chronological order of its entries. sptg = sorted(ptg, key=lambda x : x['date'],reverse=True) res = [ pinfo['slug'] for pinfo in sptg] return res
<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_default_config(self): '''Create and write to disk a default site config file.''' # maybe I should read the default config from somewhere in the package? cfg = { 'site_title': '', 'site_subtitle': '', 'default_author': '', 'site_url': '', 'default_theme': 'blog1', 'default_template': 'main.html.tpl', 'fixed_frontpage': '' } file_name = os.path.join(self._dirs['s2'],'config.yml') f = open(file_name,'w') f.write(yaml.dump(cfg,default_flow_style=False)) f.close() return cfg
<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_site_config(self): '''Read and return the site config, as a dictionary.''' file_name = os.path.join(self._dirs['s2'],'config.yml') if os.path.isfile(file_name): f = open(file_name,'r') cfg = yaml.load(f.read()) f.close() else: cfg = self._create_default_config() return cfg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def register(template_class,*extensions): ''' Register a template for a given extension or range of extensions ''' for ext in extensions: ext = normalize(ext) if not Lean.template_mappings.has_key(ext): Lean.template_mappings[ext] = [] Lean.template_mappings[ext].insert(0,template_class) Lean.template_mappings[ext] = unique(Lean.template_mappings[ext])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def is_registered(ext): ''' Returns true when a template exists on an exact match of the provided file extension ''' return Lean.template_mappings.has_key(ext.lower()) and len(Lean.template_mappings[ext])
<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(file,line=None,options={},block=None): ''' Create a new template for the given file using the file's extension to determine the the template mapping. ''' template_class = Lean.get_template(file) if template_class: return template_class(file,line,options,block) else: raise LookupError('No template engine registered for ' + os.path.basename(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 get_template(file): ''' Lookup a template class for the given filename or file extension. Return nil when no implementation is found. ''' pattern = str(file).lower() while len(pattern) and not Lean.is_registered(pattern): pattern = os.path.basename(pattern) pattern = re.sub(r'^[^.]*\.?','',pattern) # Try to find a preferred engine. preferred_klass = Lean.preferred_mappings[pattern] if Lean.preferred_mappings.has_key(pattern) else None if preferred_klass: return preferred_klass # Fall back to the general list of mappings klasses = Lean.template_mappings[pattern] # Try to find an engine which is already loaded template = None for klass in klasses: if hasattr(klass,'is_engine_initialized') and callable(klass.is_engine_initialized): if klass.is_engine_initialized(): template = klass break if template: return template # Try each of the classes until one succeeds. If all of them fails, # we'll raise the error of the first class. first_failure = None for klass in klasses: try: return klass except Exception, e: if not first_failure: first_failure = e if first_failure: raise Exception(first_failure)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(organization, package, destination): """Generates the Sphinx configuration and Makefile. Args: organization (str): the organization name. package (str): the package to be documented. destination (str): the destination directory. """
gen = ResourceGenerator(organization, package) tmp = tempfile.NamedTemporaryFile(mode='w+t', delete=False) try: tmp.write(gen.conf()) finally: tmp.close() shutil.copy(tmp.name, os.path.join(destination, 'conf.py')) tmp = tempfile.NamedTemporaryFile(mode='w+t', delete=False) try: tmp.write(gen.makefile()) finally: tmp.close() shutil.copy(tmp.name, os.path.join(destination, 'Makefile'))
<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_uri(self, content_type): "return the first self uri with the content_type" try: return [self_uri for self_uri in self.self_uri_list if self_uri.content_type == content_type][0] except IndexError: 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 pretty(self): "sort values and format output for viewing and comparing in test scenarios" pretty_obj = OrderedDict() for key, value in sorted(iteritems(self.__dict__)): if value is None: pretty_obj[key] = None elif is_str_or_unicode(value): pretty_obj[key] = self.__dict__.get(key) elif isinstance(value, list): pretty_obj[key] = [] elif isinstance(value, dict): pretty_obj[key] = {} else: pretty_obj[key] = unicode_value(value) return pretty_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 _support_directory(): """Get the path of the support_files directory"""
from os.path import join, dirname, abspath return join(dirname(abspath(__file__)), 'support_files')
<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_uo(self, configuration=None, tpl=None, keys=None, obj_type=None): """ Create a new UserObject from the given template. :param configuration: EB configuration to use :param tpl: CreateUserObject template, contain misc settings :param keys: dictionary of keys, create_uo.KeyTypes. Communication keys, application key (if applicable). :param obj_type: optional field for easy object type entry - required flags are computed from keys dict and tpl. :return: UO - user object ready to use """
if configuration is not None: self.configuration = configuration if tpl is not None: self.tpl = tpl if keys is not None: self.keys = keys if self.keys is None: self.keys = dict() # generate comm keys if not present TemplateProcessor.generate_comm_keys_if_not_present(self.keys) # obj_type infer if obj_type is not None: tpl_type = CreateUO.get_uo_type(obj_type, KeyTypes.COMM_ENC in self.keys, KeyTypes.APP_KEY in self.keys) self.tpl = CreateUO.set_type(self.tpl if self.tpl is not None else dict(), tpl_type) # Create template specifications, using local config and defaults. spec = CreateUO.get_template_request_spec(self.configuration) if self.tpl is not None: if isinstance(self.tpl, dict): spec = EBUtils.update(spec, self.tpl) else: raise ValueError('Unknown tpl format') # Fetch template for new UO. tpl_resp = CreateUO.template_request(self.configuration, spec) # Process the template, fill in the keys, do the crypto tpl_processor = TemplateProcessor(configuration=self.configuration, keys=self.keys, tpl_response=tpl_resp) tpl_req = tpl_processor.process() # Import the initialized UO self.import_resp = CreateUO.import_object(configuration=self.configuration, tpl=tpl_req) # Build UO uo = CreateUO.build_imported_object(configuration=self.configuration, tpl_import_req=tpl_req, import_resp=self.import_resp) return uo
<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_type(spec, obj_type): """ Updates type integer in the cerate UO specification. Type has to already have generations flags set correctly. Generation field is set accordingly. :param spec: :param obj_type: :return: """
if spec is None: raise ValueError('Spec cannot be None') if TemplateFields.generation not in spec: spec[TemplateFields.generation] = {} spec[TemplateFields.generation][TemplateFields.commkey] = \ Gen.CLIENT if (obj_type & (int(1) << TemplateFields.FLAG_COMM_GEN)) > 0 else Gen.LEGACY_RANDOM spec[TemplateFields.generation][TemplateFields.appkey] = \ Gen.CLIENT if (obj_type & (int(1) << TemplateFields.FLAG_APP_GEN)) > 0 else Gen.LEGACY_RANDOM spec[TemplateFields.type] = "%x" % obj_type return spec
<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_uo_type(obj_type, comm_keys_provided=True, app_keys_provided=True): """ Constructs UO type from the operation and keys provided, clears bits set ib obj_type before unless None is specified to the given parameters. :param obj_type: :param comm_keys_provided: :param app_keys_provided: :return: """
if comm_keys_provided is not None and comm_keys_provided == False: obj_type &= ~(int(1) << TemplateFields.FLAG_COMM_GEN) elif comm_keys_provided: obj_type |= (int(1) << TemplateFields.FLAG_COMM_GEN) if app_keys_provided is not None and app_keys_provided == False: obj_type &= ~(int(1) << TemplateFields.FLAG_APP_GEN) elif app_keys_provided: obj_type |= (int(1) << TemplateFields.FLAG_APP_GEN) return obj_type
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def template_request(configuration, spec): """ Calls the get template request :param configuration: :param spec: :return: """
# Template request, nonce will be regenerated. req = CreateUO.get_template_request(configuration, spec) # Do the request with retry. caller = RequestCall(req) resp = caller.call() return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_imported_object(configuration, tpl_import_req, import_resp): """ Builds uo from the imported object to the EB. Imported object = result of CreateUserObject call in EB. Returns usable uo - you may call ProcessData with it. """
if import_resp is None \ or import_resp.response is None \ or 'result' not in import_resp.response \ or 'handle' not in import_resp.response['result']: logger.info('Invalid result: %s', import_resp) raise InvalidResponse('Invalid import result') # TEST_API00000022480000300004 handle = import_resp.response['result']['handle'] handle_len = len(handle) api_key = handle[0: handle_len-10-10] uo_id_str = handle[handle_len-10-10+2: handle_len-10] uo_type_str = handle[handle_len-10+2:] uo_id = bytes_to_long(from_hex(uo_id_str)) uo_type = bytes_to_long(from_hex(uo_type_str)) uo = UO(uo_id=uo_id, uo_type=uo_type, enc_key=tpl_import_req.keys[KeyTypes.COMM_ENC].key, mac_key=tpl_import_req.keys[KeyTypes.COMM_MAC].key) uo.configuration = configuration # Store API key only if it differs from slot. if configuration is not None and configuration.api_key != api_key: uo.api_key = api_key return uo
<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_serialized_rsa_pub_key(serialized): """ Reads serialized RSA pub key TAG|len-2B|value. 81 = exponent, 82 = modulus :param serialized: :return: n, e """
n = None e = None rsa = from_hex(serialized) pos = 0 ln = len(rsa) while pos < ln: tag = bytes_to_byte(rsa, pos) pos += 1 length = bytes_to_short(rsa, pos) pos += 2 if tag == 0x81: e = bytes_to_long(rsa[pos:pos+length]) elif tag == 0x82: n = bytes_to_long(rsa[pos:pos+length]) pos += length if e is None or n is None: logger.warning("Could not process import key") raise ValueError('Public key deserialization failed') return n, e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def env(var_name, default=False): """ Get the environment variable or assume a default, but let the user know about the error."""
try: value = os.environ[var_name] if str(value).strip().lower() in ['false', 'no', 'off' '0', 'none', 'null']: return None return value except: from traceback import format_exc msg = format_exc() + '\n' + "Unable to find the %s environment variable.\nUsing the value %s (the default) instead.\n" % (var_name, default) warnings.warn(msg) 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 check_negated_goals(self,safe_variables,query): ''' Create a list of variables which occur in negated goals. ''' variables_in_negated_goals = \ [y for x in query.relations for y in list(x.variables) if x.is_negated()] # And check them: for variable in variables_in_negated_goals: if not (variable in safe_variables): raise NotSafeException('Query not safe because ' + \ variable.name + \ ' from a negated goal does not occur in a positive goal') return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_non_equality_explicit_constraints(self,safe_variables,query): ''' Checking variables which occur in explicit constraints with non equality operators ''' # Create a list of variables which occur in explicit constraints with non # equality operators variables_in_constraints_with_non_equality_operators = \ [y for x in query.constraints \ for y in [x.get_left_side(), x.get_right_side()] \ if y.is_variable() and not x.is_equality_constraint()] for variable in variables_in_constraints_with_non_equality_operators: if not (variable in safe_variables): raise NotSafeException('Query not safe because ' + \ variable.name + \ ' from a non_equality comparison does not occur in a positive goal') return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_database(destroy_existing=False): """ Create db and tables if it doesn't exist """
if not os.path.exists(DB_NAME): logger.info('Create database: {0}'.format(DB_NAME)) open(DB_NAME, 'a').close() Show.create_table() Episode.create_table() Setting.create_table()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def magic_api(word): """ This is our magic API that we're simulating. It'll return a random number and a cache timer. """
result = sum(ord(x)-65 + randint(1,50) for x in word) delta = timedelta(seconds=result) cached_until = datetime.now() + delta return result, cached_until
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def portfolio_prices( symbols=("AAPL", "GLD", "GOOG", "$SPX", "XOM", "msft"), start=datetime.datetime(2005, 1, 1), end=datetime.datetime(2011, 12, 31), # data stops at 2013/1/1 normalize=True, allocation=None, price_type='actual_close', ): """Calculate the Sharpe Ratio and other performance metrics for a portfolio Arguments: symbols (list of str): Ticker symbols like "GOOG", "AAPL", etc start (datetime): The date at the start of the period being analyzed. end (datetime): The date at the end of the period being analyzed. normalize (bool): Whether to normalize prices to 1 at the start of the time series. allocation (list of float): The portion of the portfolio allocated to each equity. """
symbols = normalize_symbols(symbols) start = util.normalize_date(start) end = util.normalize_date(end) if allocation is None: allocation = [1. / len(symbols)] * len(symbols) if len(allocation) < len(symbols): allocation = list(allocation) + [1. / len(symbols)] * (len(symbols) - len(allocation)) total = np.sum(allocation.sum) allocation = np.array([(float(a) / total) for a in allocation]) timestamps = du.getNYSEdays(start, end, datetime.timedelta(hours=16)) ls_keys = [price_type] ldf_data = da.get_data(timestamps, symbols, ls_keys) d_data = dict(zip(ls_keys, ldf_data)) na_price = d_data[price_type].values if normalize: na_price /= na_price[0, :] na_price *= allocation return np.sum(na_price, axis=1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def symbol_bollinger(symbol='GOOG', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='close', cleaner=clean_dataframe, window=20, sigma=1.): """Calculate the Bolinger indicator value """
symbols = normalize_symbols(symbol) prices = price_dataframe(symbols, start=start, end=end, price_type=price_type, cleaner=cleaner) return series_bollinger(prices[symbols[0]], window=window, sigma=sigma, plot=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 symbols_bollinger(symbols='sp5002012', start=datetime.datetime(2008, 1, 1), end=datetime.datetime(2009, 12, 31), price_type='adjusted_close', cleaner=clean_dataframe, window=20, sigma=1.): """Calculate the Bolinger for a list or set of symbols Example: GOOG AAPL IBM MSFT 2010-12-23 16:00:00 1.298178 1.185009 1.177220 1.237684 2010-12-27 16:00:00 1.073603 1.371298 0.590403 0.932911 2010-12-28 16:00:00 0.745548 1.436278 0.863406 0.812844 2010-12-29 16:00:00 0.874885 1.464894 2.096242 0.752602 2010-12-30 16:00:00 0.634661 0.793493 1.959324 0.498395 """
symbols = normalize_symbols(symbols) prices = price_dataframe(symbols, start=start, end=end, price_type=price_type, cleaner=cleaner) return frame_bollinger(prices, window=window, sigma=sigma, plot=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 metrics(prices, fudge=False, sharpe_days=252., baseline='$SPX'): """Calculate the volatiliy, average daily return, Sharpe ratio, and cumulative return Arguments: prices (file or basestring or iterable): path to file or file pointer or sequence of prices/values of a portfolio or equity fudge (bool): Whether to use Tucker Balche's erroneous division by N or the more accurate N-1 for stddev of returns sharpe_days: Number of trading days in a year. Sharpe ratio = sqrt(sharpe_days) * total_return / std_dev_of_daily_returns Examples: True True """
if isinstance(prices, basestring) and os.path.isfile(prices): prices = open(prices, 'rU') if isinstance(prices, file): values = {} csvreader = csv.reader(prices, dialect='excel', quoting=csv.QUOTE_MINIMAL) for row in csvreader: # print row values[tuple(int(s) for s in row[:3])] = row[-1] prices.close() prices = [v for (k,v) in sorted(values.items())] print prices if isinstance(prices[0], (tuple, list)): prices = [row[-1] for row in prices] if sharpe_days == None: sharpe_days = len(prices) prices = np.array([float(p) for p in prices]) if not isinstance(fudge, bool) and fudge: fudge = float(fudge) elif fudge == True or (isinstance(fudge, float) and fudge == 0.0): fudge = (len(prices) - 1.) / len(prices) else: fudge = 1.0 daily_returns = np.diff(prices) / prices[0:-1] # print daily_returns end_price = float(prices[-1]) start_price = (prices[0]) mean = fudge * np.average(daily_returns) variance = fudge * np.sum((daily_returns - mean) * (daily_returns - mean)) / float(len(daily_returns)) results = { 'standared deviation of daily returns': math.sqrt(variance), 'variance of daily returns': variance, 'average daily return': mean, 'Sharpe ratio': mean * np.sqrt(sharpe_days) / np.sqrt(variance), 'total return': end_price / start_price, 'final value': end_price, 'starting value': start_price, } results['return rate'] = results['total return'] - 1.0 return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def buy_on_drop(symbol_set="sp5002012", dataobj=dataobj, start=datetime.datetime(2008, 1, 3), end=datetime.datetime(2009, 12, 28), market_sym='$SPX', threshold=6, sell_delay=5, ): '''Compute and display an "event profile" for multiple sets of symbols''' if symbol_set: if isinstance(symbol_set, basestring): if symbol_set.lower().startswith('sp'): symbol_set = dataobj.get_symbols_from_list(symbol_set.lower()) else: symbol_set = [sym.stip().upper() for sym in symbol_set.split(",")] else: symbol_set = dataobj.get_symbols_from_list("sp5002012") if market_sym: symbol_set.append(market_sym) print "Starting Event Study, retrieving data for the {0} symbol list...".format(symbol_set) market_data = get_clean_prices(symbol_set, dataobj=dataobj, start=start, end=end) print "Finding events for {0} symbols between {1} and {2}...".format(len(symbol_set), start, end) trigger_kwargs={'threshold': threshold} events = find_events(symbol_set, market_data, market_sym=market_sym, trigger=drop_below, trigger_kwargs=trigger_kwargs) csvwriter = csv.writer(getattr(args, 'outfile', open('buy_on_drop_outfile.csv', 'w')), dialect='excel', quoting=csv.QUOTE_MINIMAL) for order in generate_orders(events, sell_delay=sell_delay, sep=None): csvwriter.writerow(order) print "Creating Study report for {0} events...".format(len(events)) ep.eventprofiler(events, market_data, i_lookback=20, i_lookforward=20, s_filename='Event report--buy on drop below {0} for {1} symbols.pdf'.format(threshold, len(symbol_set)), b_market_neutral=True, b_errorbars=True, s_market_sym=market_sym, ) return events
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_orders(events, sell_delay=5, sep=','): """Generate CSV orders based on events indicated in a DataFrame Arguments: events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol. 1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent. sell_delay (float): Number of days to wait before selling back the shares bought sep (str or None): if sep is None, orders will be returns as tuples of `int`s, `float`s, and `str`s otherwise the separator will be used to join the order parameters into the yielded str Returns: generator of str: yielded CSV rows in the format (yr, mo, day, symbol, Buy/Sell, shares) """
sell_delay = float(unicode(sell_delay)) or 1 for i, (t, row) in enumerate(events.iterrows()): for sym, event in row.to_dict().iteritems(): # print sym, event, type(event) # return events if event and not np.isnan(event): # add a sell event `sell_delay` in the future within the existing `events` DataFrame # modify the series, but only in the future and be careful not to step on existing events if event > 0: sell_event_i = min(i + sell_delay, len(events) - 1) sell_event_t = events.index[sell_event_i] sell_event = events[sym][sell_event_i] if np.isnan(sell_event): events[sym][sell_event_t] = -1 else: events[sym][sell_event_t] += -1 order = (t.year, t.month, t.day, sym, 'Buy' if event > 0 else 'Sell', abs(event) * 100) if isinstance(sep, basestring): yield sep.join(order) yield order
<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_file(save_path, file_url): """ Download file from http url link """
r = requests.get(file_url) # create HTTP response object with open(save_path, 'wb') as f: f.write(r.content) return save_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 make_url(domain, location): """ This function helps to make full url path."""
url = urlparse(location) if url.scheme == '' and url.netloc == '': return domain + url.path elif url.scheme == '': return 'http://' + url.netloc + url.path else: return url.geturl()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getlist(self, key): """Returns a Storage value as a list. If the value is a list it will be returned as-is. If object is None, an empty list will be returned. Otherwise, `[value]` will be returned. Example output for a query string of `?x=abc&y=abc&y=def`:: ['abc'] ['abc', 'def'] [] """
value = self.get(key, []) if value is None or isinstance(value, (list, tuple)): return value else: return [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 getfirst(self, key, default=None): """Returns the first value of a list or the value itself when given a `request.vars` style key. If the value is a list, its first item will be returned; otherwise, the value will be returned as-is. Example output for a query string of `?x=abc&y=abc&y=def`:: 'abc' 'abc' """
values = self.getlist(key) return values[0] if values else 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 getlast(self, key, default=None): """Returns the last value of a list or value itself when given a `request.vars` style key. If the value is a list, the last item will be returned; otherwise, the value will be returned as-is. Simulated output with a query string of `?x=abc&y=abc&y=def`:: 'abc' 'def' """
values = self.getlist(key) return values[-1] if values else 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 _eval_variables(self): """evaluates callable _variables """
for k, v in listitems(self._variables): self._variables[k] = v() if hasattr(v, '__call__') else 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 defer(callable): '''Defers execution of the callable to a thread. For example: >>> def foo(): ... print('bar') >>> join = defer(foo) >>> join() ''' t = threading.Thread(target=callable) t.start() return t.join
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def close_fds(): '''Close extraneous file descriptors. On Linux, close everything but stdin, stdout, and stderr. On Mac, close stdin, stdout, and stderr and everything owned by our user id. ''' def close(fd): with ignored(OSError): os.close(fd) if sys.platform == 'linux': fd_dir = '/proc/self/fd' fds = set(map(int, os.listdir(fd_dir))) for x in (fds - {0, 1, 2}): close(x) elif sys.platform == 'darwin': uid = os.getuid() fd_dir = '/dev/fd' fds = set(map(int, os.listdir(fd_dir))) for x in (fds - {0, 1, 2}): path = '/dev/fd/' + str(x) if not os.access(path, os.R_OK): continue stat = os.fstat(x) if stat.st_uid != uid: continue close(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, extension: Extension) -> 'DictMentor': """ Add any predefined or custom extension. Args: extension: Extension to add to the processor. Returns: The DictMentor itself for chaining. """
if not Extension.is_valid_extension(extension): raise ValueError("Cannot bind extension due to missing interface requirements") self._extensions.append(extension) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def augment(self, dct: NonAugmentedDict, document: Optional[YamlDocument] = None) -> AugmentedDict: """ Augments the given dictionary by using all the bound extensions. Args: dct: Dictionary to augment. document: The document the dictionary was loaded from. Returns: The augmented dictionary. """
Validator.instance_of(dict, raise_ex=True, dct=dct) # Apply any configured loader for instance in self._extensions: nodes = list(dict_find_pattern(dct, **instance.config())) for parent, k, val in nodes: parent.pop(k) fragment = instance.apply( ExtensionContext( mentor=self, document=document or dct, dct=dct, parent_node=parent, node=(k, val) ) ) if fragment is not None: parent.update(fragment) return dct
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Date(value): """Custom type for managing dates in the command-line."""
from datetime import datetime try: return datetime(*reversed([int(val) for val in value.split('/')])) except Exception as err: raise argparse.ArgumentTypeError("invalid date '%s'" % 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(clients_num, clients_host, clients_port, people_num, throttle): """ Prepare clients to execute :return: Modules to execute, cmd line function :rtype: list[WrapperClient], (str, object) -> str | None """
res = [] for number in range(clients_num): sc = EchoClient({ 'id': number, 'listen_bind_ip': clients_host, #'multicast_bind_ip': "127.0.0.1", 'listen_port': clients_port + number }) people = [] for person_number in range(people_num): people.append(Person(id=person_number)) wrapper = WrapperEchoClient({ 'client': sc, 'people': people, 'throttle': throttle }) res.append(wrapper) return res, cmd_line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _packet_loop(self): """ Packet processing loop :rtype: None """
while self._is_running: # Only wait if there are no more packets in the inbox if self.inbox.empty() \ and not self.new_packet.wait(self._packet_timeout): continue ip, port, packet = self.inbox.get() if self.inbox.empty(): self.new_packet.clear() self.debug(u"{}".format(packet)) if packet.header.message_type == MsgType.CONFIG: self._do_config_packet(packet, ip, port) elif packet.header.message_type == MsgType.UPDATE: self._do_update_packet(packet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dechex(num,zfill=0): ''' Simple integer to hex converter. The zfill is the number of bytes, even though the input is a hex string, which means that the actual zfill is 2x what you might initially think it would be. For example: >>> dechex(4,2) '0004' ''' if not isitint(num): raise TypeError("Input must be integer/long.") o = hex(num).lstrip("0x").rstrip("L") if o == "" or o == "0": o = '00' try: o = unhexlify(o) except: o = unhexlify("0"+o) if o == b'\x00' or o == 0: o = '00' else: o = hexstrlify(o) for i in range((2*zfill)-len(o)): o = "0" + o if len(o) % 2: o = "0" + o return str(o)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def selenol_params(**kwargs): """Decorate request parameters to transform them into Selenol objects."""
def params_decorator(func): """Param decorator. :param f: Function to decorate, typically on_request. """ def service_function_wrapper(service, message): """Wrap function call. :param service: SelenolService object. :param message: SelenolMessage request. """ params = {k: f(service, message) for k, f in kwargs.items()} return func(service, **params) return service_function_wrapper return params_decorator
<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_value(data_structure, key): """Return the value of a data_structure given a path. :param data_structure: Dictionary, list or subscriptable object. :param key: Array with the defined path ordered. """
if len(key) == 0: raise KeyError() value = data_structure[key[0]] if len(key) > 1: return _get_value(value, key[1:]) return 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 get_value_from_session(key): """Get a session value from the path specifed. :param key: Array that defines the path of the value inside the message. """
def value_from_session_function(service, message): """Actual implementation of get_value_from_session function. :param service: SelenolService object. :param message: SelenolMessage request. """ return _get_value(message.session, key) return value_from_session_function
<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_value_from_content(key): """Get a value from the path specifed. :param key: Array that defines the path of the value inside the message. """
def value_from_content_function(service, message): """Actual implementation of get_value_from_content function. :param service: SelenolService object. :param message: SelenolMessage request. """ return _get_value(message.content, key) return value_from_content_function
<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_object_from_content(entity, key): """Get an object from the database given an entity and the content key. :param entity: Class type of the object to retrieve. :param key: Array that defines the path of the value inside the message. """
def object_from_content_function(service, message): """Actual implementation of get_object_from_content function. :param service: SelenolService object. :param message: SelenolMessage request. """ id_ = get_value_from_content(key)(service, message) result = service.session.query(entity).get(id_) if not result: raise SelenolInvalidArgumentException(key, id_) return result return object_from_content_function
<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_object_from_session(entity, key): """Get an object from the database given an entity and the session key. :param entity: Class type of the object to retrieve. :param key: Array that defines the path of the value inside the message. """
def object_from_session_function(service, message): """Actual implementation of get_object_from_session function. :param service: SelenolService object. :param message: SelenolMessage request. """ id_ = get_value_from_session(key)(service, message) result = service.session.query(entity).get(id_) if not result: raise SelenolInvalidArgumentException(key, id_) return result return object_from_session_function
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _process_json(data): """ return a list of GradPetition objects. """
requests = [] for item in data: petition = GradPetition() petition.description = item.get('description') petition.submit_date = parse_datetime(item.get('submitDate')) petition.decision_date = parse_datetime(item.get('decisionDate')) if item.get('deptRecommend') and len(item.get('deptRecommend')): petition.dept_recommend = item.get('deptRecommend').lower() if item.get('gradSchoolDecision') and\ len(item.get('gradSchoolDecision')): petition.gradschool_decision =\ item.get('gradSchoolDecision').lower() requests.append(petition) return requests
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example_add_line_to_file(): """ Different methods to append a given line to the file, all work the same. """
my_file = FileAsObj('/tmp/example_file.txt') my_file.add('foo') my_file.append('bar') # Add a new line to my_file that contains the word 'lol' and print True|False if my_file was changed. print(my_file + 'lol') # Add line even if it already exists in the file. my_file.unique = False my_file.add('foo')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example_write_file_to_disk_if_changed(): """ Try to remove all comments from a file, and save it if changes were made. """
my_file = FileAsObj('/tmp/example_file.txt') my_file.rm(my_file.egrep('^#')) if my_file.changed: my_file.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def example_all(): """ Use a bunch of methods on a file. """
my_file = FileAsObj() my_file.filename = '/tmp/example_file.txt' my_file.add('# First change!') my_file.save() my_file = FileAsObj('/tmp/example_file.txt') my_file.unique = True my_file.sorted = True my_file.add('1') my_file.add('1') my_file.add('2') my_file.add('20 foo') my_file.add('200 bar') my_file.add('# Comment') my_file.unique = False my_file.add('# Comment') my_file.add('# Comment') my_file.unique = True my_file.rm(my_file.egrep('^#.*')) my_file.rm(my_file.grep('foo')) my_file.replace(my_file.egrep('^2'), 'This line was replaced.') print(my_file) print(my_file.log)
<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_cal_data(data_df, cal_dict, param): '''Get data along specified axis during calibration intervals Args ---- data_df: pandas.DataFrame Pandas dataframe with lleo data cal_dict: dict Calibration dictionary Returns ------- lower: pandas dataframe slice of lleo datafram containing points at -1g calibration position upper: pandas dataframe slice of lleo datafram containing points at -1g calibration position See also -------- lleoio.read_data: creates pandas dataframe `data_df` read_cal: creates `cal_dict` and describes fields ''' param = param.lower().replace(' ','_').replace('-','_') idx_lower_start = cal_dict['parameters'][param]['lower']['start'] idx_lower_end = cal_dict['parameters'][param]['lower']['end'] idx_upper_start = cal_dict['parameters'][param]['upper']['start'] idx_upper_end = cal_dict['parameters'][param]['upper']['end'] idx_lower = (data_df.index >= idx_lower_start) & \ (data_df.index <= idx_lower_end) idx_upper = (data_df.index >= idx_upper_start) & \ (data_df.index <= idx_upper_end) return data_df[param][idx_lower], data_df[param][idx_upper]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def read_cal(cal_yaml_path): '''Load calibration file if exists, else create Args ---- cal_yaml_path: str Path to calibration YAML file Returns ------- cal_dict: dict Key value pairs of calibration meta data ''' from collections import OrderedDict import datetime import os import warnings import yamlord from . import utils def __create_cal(cal_yaml_path): cal_dict = OrderedDict() # Add experiment name for calibration reference base_path, _ = os.path.split(cal_yaml_path) _, exp_name = os.path.split(base_path) cal_dict['experiment'] = exp_name return cal_dict # Try reading cal file, else create if os.path.isfile(cal_yaml_path): cal_dict = yamlord.read_yaml(cal_yaml_path) else: cal_dict = __create_cal(cal_yaml_path) cal_dict['parameters'] = OrderedDict() for key, val in utils.parse_experiment_params(cal_dict['experiment']).items(): cal_dict[key] = val fmt = "%Y-%m-%d %H:%M:%S" cal_dict['date_modified'] = datetime.datetime.now().strftime(fmt) return cal_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(data_df, cal_dict, param, bound, start, end): '''Update calibration times for give parameter and boundary''' from collections import OrderedDict if param not in cal_dict['parameters']: cal_dict['parameters'][param] = OrderedDict() if bound not in cal_dict['parameters'][param]: cal_dict['parameters'][param][bound] = OrderedDict() cal_dict['parameters'][param][bound]['start'] = start cal_dict['parameters'][param][bound]['end'] = end return cal_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fit1d(lower, upper): '''Fit acceleration data at lower and upper boundaries of gravity Args ---- lower: pandas dataframe slice of lleo datafram containing points at -1g calibration position upper: pandas dataframe slice of lleo datafram containing points at -1g calibration position Returns ------- p: ndarray Polynomial coefficients, highest power first. If y was 2-D, the coefficients for k-th data set are in p[:,k]. From `numpy.polyfit()`. NOTE ---- This method should be compared agaist alternate linalg method, which allows for 2d for 2d poly, see - http://stackoverflow.com/a/33966967/943773 A = numpy.vstack(lower, upper).transpose() y = A[:,1] m, c = numpy.linalg.lstsq(A, y)[0] ''' import numpy # Get smallest size as index position for slicing idx = min(len(lower), len(upper)) # Stack accelerometer count values for upper and lower bounds of curve x = numpy.hstack((lower[:idx].values, upper[:idx].values)) x = x.astype(float) # Make corresponding y array where all lower bound points equal -g # and all upper bound points equal +g y = numpy.zeros(len(x), dtype=float) y[:idx] = -1.0 # negative gravity y[idx:] = 1.0 # positive gravity return numpy.polyfit(x, y, deg=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 un_comment(s, comment='#', strip=True): """Uncomment a string or list of strings truncate s at first occurrence of a non-escaped comment character remove escapes from escaped comment characters Parameters: s - string to uncomment comment - comment character (default=#) (see Note 1) strip - strip line after uncomment (default=True) Notes: 1. Comment character can be escaped using \ 2. If a tuple or list is provided, a list of the same length will be returned, with each string in the list uncommented. Some lines may be zero length. """
def _un_comment(string): result = re.split(r'(?<!\\)' + comment, string, maxsplit=1)[0] result = re.sub(r'\\' + comment, comment, result) if strip: return result.strip() return result if isinstance(s, (tuple, list)): return [_un_comment(line) for line in s] return _un_comment(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_smooth_step_function(min_val, max_val, switch_point, smooth_factor): """Returns a function that moves smoothly between a minimal value and a maximal one when its value increases from a given witch point to infinity. Arguments --------- min_val: float max_val value the function will return when x=switch_point. min_val: float The value the function will converge to when x -> infinity. switch_point: float The point in which the function's value will become min_val. Smaller x values will return values smaller than min_val. smooth_factor: float The bigger the smoother, and less cliff-like, is the function. Returns ------- function The desired smooth function. """
dif = max_val - min_val def _smooth_step(x): return min_val + dif * tanh((x - switch_point) / smooth_factor) return _smooth_step
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stack_sources(): """A list of sources for frames above this"""
# lazy imports import linecache result = [] for frame_info in reversed(inspect.stack()): _frame, filename, line_number, _function, _context, _index = frame_info linecache.lazycache(filename, {}) _line = linecache.getline(filename, line_number).rstrip() # Each record contains a frame object, filename, line number, function # name, a list of lines of context, and index within the context _sources = [(path, line) for _, path, line, _, _, _ in inspect.stack()] 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 extract_leftmost_selector(selector_list): """ Because we aren't building a DOM tree to transverse, the only way to get the most general selectors is to take the leftmost. For example with `div.outer div.inner`, we can't tell if `div.inner` has been used in context without building a tree. """
classes = set() ids = set() elements = set() # print "Selector list: %s \n\n\n\n\n\n" % selector_list for selector in selector_list: selector = selector.split()[0] if selector[0] == '.': classes.add(selector) elif selector[0] == '#': ids.add(selector) else: elements.add(selector) return { 'classes':classes, 'ids':ids, 'elements':elements, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append_styles(self, tag, attrs): """ Append classes found in HTML elements to the list of styles used. Because we haven't built the tree, we aren't using the `tag` parameter for now. @param <string> tag The HTML tag we're parsing @param <tuple> attrs A tuple of HTML element attributes such as 'class', 'id', 'style', etc. The tuple is of the form ('html_attribute', """
dattrs = dict(attrs) if 'class' in dattrs: #print "Found classes '%s'" % dattrs['class'] class_names = dattrs['class'].split() dotted_names = map(prepend_dot,class_names) dotted_names.sort() self.used_classes.extend(' '.join(dotted_names)) self.unchained_classes.extend(dotted_names) if 'id' in dattrs: #print "Found id '%s'" % dattrs['id'] self.used_ids.extend(prepend_hash(dattrs['id'].strip()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_after(filename): """Decorator to be sure the file given by parameter is deleted after the execution of the method. """
def delete_after_decorator(function): def wrapper(*args, **kwargs): try: return function(*args, **kwargs) finally: if os.path.isfile(filename): os.remove(filename) if os.path.isdir(filename): shutil.rmtree(filename) return wrapper return delete_after_decorator
<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_geocode(city, state, street_address="", zipcode=""): """ For given location or object, takes address data and returns latitude and longitude coordinates from Google geocoding service get_geocode(self, street_address="1709 Grand Ave.", state="MO", zip="64112") Returns a tuple of (lat, long) Most times you'll want to join the return. """
try: key = settings.GMAP_KEY except AttributeError: return "You need to put GMAP_KEY in settings" # build valid location string location = "" if street_address: location += '{}+'.format(street_address.replace(" ", "+")) location += '{}+{}'.format(city.replace(" ", "+"), state) if zipcode: location += "+{}".format(zipcode) url = "http://maps.google.com/maps/geo?q={}&output=xml&key={}".format(location, key) file = urllib.urlopen(url).read() try: xml = xmltramp.parse(file) except Exception as error: print("Failed to parse xml file {}: {}".format(file, error)) return None status = str(xml.Response.Status.code) if status == "200": geocode = str(xml.Response.Placemark.Point.coordinates).split(',') # Flip geocode because geocoder returns long/lat while Maps wants lat/long. # Yes, it's dumb. return (geocode[1], geocode[0]) else: print(status) 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 list(self,walkTrace=tuple(),case=None,element=None): """List section titles. """
if case == 'sectionmain': print(walkTrace,self.title)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listFigures(self,walkTrace=tuple(),case=None,element=None): """List section figures. """
if case == 'sectionmain': print(walkTrace,self.title) if case == 'figure': caption,fig = element try: print(walkTrace,fig._leopardref,caption) except AttributeError: fig._leopardref = next(self._reportSection._fignr) print(walkTrace,fig._leopardref,caption)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listTables(self,walkTrace=tuple(),case=None,element=None): """List section tables. """
if case == 'sectionmain': print(walkTrace,self.title) if case == 'table': caption,tab = element try: print(walkTrace,tab._leopardref,caption) except AttributeError: tab._leopardref = next(self._reportSection._tabnr) print(walkTrace,tab._leopardref,caption)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sectionOutZip(self,zipcontainer,zipdir='',figtype='png'): """Prepares section for zip output """
from io import StringIO, BytesIO text = self.p if not self.settings['doubleslashnewline'] else self.p.replace('//','\n') zipcontainer.writestr( zipdir+'section.txt', '# {}\n{}'.format(self.title,text).encode() ) c = count(1) for ftitle,f in self.figs.items(): figfile = zipdir+'fig{}_{}.{}'.format(next(c),ftitle.replace(' ','_'),figtype) b = BytesIO() f.savefig(b,format=figtype,transparent=True) b.seek(0) zipcontainer.writestr(figfile,b.getvalue()) c = count(1) for ttitle,t in self.tabs.items(): b = StringIO() t.to_csv(b,sep=csvsep,decimal=csvdec) b.seek(0) zipcontainer.writestr( zipdir+'table{}_{}.csv'.format(next(c),ttitle.replace(' ','_')), b.read().encode() ) c = count(1) for s in self.subs: s.sectionOutZip(zipcontainer,'{}s{}_{}/'.format(zipdir,next(c),s.title.replace(' ','_')),figtype=figtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sectionsWord(self,walkTrace=tuple(),case=None,element=None,doc=None): """Prepares section for word output. """
from docx.shared import Inches from io import BytesIO #p.add_run('italic.').italic = True if case == 'sectionmain': if self.settings['clearpage']: doc.add_page_break() doc.add_heading(self.title, level = len(walkTrace)) for p in renewliner(self.p).split('\n'): doc.add_paragraph(p) if case == 'figure': bf=BytesIO() figtitle,fig = element width = fig.get_size_inches()[0] width = Inches(width if width < 6 else 6) fig.savefig(bf) doc.add_picture(bf, width=width) doc.add_heading('Figure {}: {}'.format( fig._leopardref, figtitle),level=6) if case == 'table': caption,t = element tableref = t._leopardref t = pdSeriesToFrame(t) if type(t) == pd.Series else t if self.settings['tablehead']: t = t.head(self.settings['tablehead']) if self.settings['tablecolumns']: t = t[self.settings['tablecolumns']] doc.add_heading('Table {}: {}'.format( tableref, caption),level=6) table = doc.add_table(t.shape[0]+1,t.shape[1]+1) for tcell,col in zip(table.rows[0].cells[1:],t.columns): tcell.text = str(col) for trow,rrow in zip(table.rows[1:],t.to_records()): for tcell,rcell in zip(trow.cells,rrow): tcell.text = str(rcell)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sectionFromFunction(function,*args,**kwargs): """ This staticmethod executes the function that is passed with the provided args and kwargs. The first line of the function docstring is used as the section title, the comments within the function body are parsed and added as the section text. The function should return an ordered dict of figures and tables, that are then attached to the section. Args: function (function): The function that generates the section content. Returns: Section <Section @ Section title of example function> """
figures, tables = function(*args,**kwargs) title = inspect.getcomments(function)[1:].strip() text = inspect.getdoc(function) code = inspect.getsource(function) return Section(title=title,text=text,figures=figures,tables=tables,code=code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list(self): """ Get an overview of the report content list """
for i in range(len(self.sections)): self.sections[i].list(walkTrace=(i+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 outputZip(self,figtype='png'): """ Outputs the report in a zip container. Figs and tabs as pngs and excells. Args: figtype (str): Figure type of images in the zip folder. """
from zipfile import ZipFile with ZipFile(self.outfile+'.zip', 'w') as zipcontainer: zipcontainer.writestr( 'summary.txt', '# {}\n\n{}\n{}'.format( self.title, self.p, ('\n## Conclusion\n' if self.conclusion else '')+self.conclusion ).encode() ) c = count(1) for section in self.sections: section.sectionOutZip(zipcontainer,'s{}_{}/'.format(next(c),section.title.replace(' ','_')), figtype=figtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def outputWord(self): """Output report to word docx """
import docx from docx.enum.text import WD_ALIGN_PARAGRAPH doc = docx.Document() doc.styles['Normal'].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY doc.add_heading(self.title, level=0) if self.addTime: from time import localtime, strftime doc.add_heading(strftime("%Y-%m-%d %H:%M:%S", localtime()), level=1) # Append introduction if self.p: doc.add_heading('Introduction',level=1) for p in renewliner(self.p).split('\n'): doc.add_paragraph(p) # Sections c = count(1) #Prepare fig and table numbers self.listFigures(tuple()) self.listTables(tuple()) for section in self.sections: section.sectionsWord((next(c),),doc=doc) # Append conclusion if self.conclusion: doc.add_heading('Conclusion', level=1) for p in renewliner(self.conclusion).split('\n'): doc.add_paragraph(p) # Generate Word document doc.save(self.outfile+'.docx')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getReportTable(reportzipfile,tablefilename,inReportsDir=True,verbose=False): """Get a pandas table from a previous report Args: reportzipfile (str): Zip folder location, '.zip' extension is optional. tablefilename (str or list int): Table location within the zip folder. Can be provided as the filename within the zip folder, or a list of integers indicating its exact position (1-indexed). If you provide an empty string or list, all available table filenames in the zip folder will be printed. inReportsDir (bool): Search reportzipfile relative to reportsDir. Returns: pd.DataFrame """
import zipfile, io, re # zipfilename preparation if not reportzipfile.endswith('.zip'): reportzipfile+='.zip' if inReportsDir: reportzipfile = os.path.join(reportsDir,reportzipfile) with zipfile.ZipFile(reportzipfile) as z: # print all table filenames if tablefilename is not provided if not tablefilename: for f in z.filelist: if 'table' in f.filename: print(f.filename) return # tablefilename preparation if int list if isinstance(tablefilename,list): tablelocation = tablefilename tablefilename = None location = re.compile(r'(s|table)(\d+)_') for f in z.filelist: if 'table' not in f.filename or f.filename.count('/') != (len(tablelocation)-1): continue if [int(location.match(s).groups()[1]) for s in f.filename.split('/')] == tablelocation: tablefilename = f.filename if verbose: print('Loading',tablefilename) break if tablefilename is None: raise FileNotFoundError('Table location not found in zip folder.') # read table with z.open(tablefilename) as f: ft = io.TextIOWrapper(f) return pd.read_csv(ft,index_col=0,sep=csvsep,decimal=csvdec)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform_standard_normal(df): """Transform a series or the rows of a dataframe to the values of a standard normal based on rank."""
import pandas as pd import scipy.stats as stats if type(df) == pd.core.frame.DataFrame: gc_ranks = df.rank(axis=1) gc_ranks = gc_ranks / (gc_ranks.shape[1] + 1) std_norm = stats.norm.ppf(gc_ranks) std_norm = pd.DataFrame(std_norm, index=gc_ranks.index, columns=gc_ranks.columns) elif type(df) == pd.core.series.Series: gc_ranks = df.rank() gc_ranks = gc_ranks / (gc_ranks.shape[0] + 1) std_norm = stats.norm.ppf(gc_ranks) std_norm = pd.Series(std_norm, index=df.index) return std_norm
<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_gzipped_text_url(url): """Read a gzipped text file from a URL and return contents as a string."""
import urllib2 import zlib from StringIO import StringIO opener = urllib2.build_opener() request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip') respond = opener.open(request) compressedData = respond.read() respond.close() opener.close() compressedDataBuf = StringIO(compressedData) d = zlib.decompressobj(16+zlib.MAX_WBITS) buffer = compressedDataBuf.read(1024) #saveFile = open('/tmp/test.txt', "wb") s = [] while buffer: s.append(d.decompress(buffer)) buffer = compressedDataBuf.read(1024) s = ''.join(s) 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_worst_flag_level(self, flags): ''' Determines the worst flag present in the provided flags. If no flags are given then a 'minor' value is returned. ''' worst_flag_level = 0 for flag_level_name in flags: flag_level = self.FLAG_LEVELS[flag_level_name] if flag_level > worst_flag_level: worst_flag_level = flag_level return self.FLAG_LEVEL_CODES[worst_flag_level]
<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(line): """ Parse accesslog line to map Python dictionary. Returned dictionary has following keys: - time: access time (datetime; naive) - utcoffset: UTC offset of access time (timedelta) - host: remote IP address. - path: HTTP request path, this will be splitted from query. - query: HTTP requert query string removed from "?". - method: HTTP request method. - protocol: HTTP request version. - status: HTTP response status code. (int) - size: HTTP response size, if available. (int) - referer: Referer header. if "-" is given, that will be ignored. - ua: User agent. if "-" is given, that will be ignored. - ident: remote logname - user: remote user - trailing: Additional information if using custom log format. You can use "utcoffset" with `dateutil.tz.tzoffset` like followings: :param line: one line of access log combined format :type line: string :rtype: dict """
m = LOG_FORMAT.match(line) if m is None: return access = Access._make(m.groups()) entry = { 'host': access.host, 'path': access.path, 'query': access.query, 'method': access.method, 'protocol': access.protocol, 'status': int(access.status) } entry['time'] = datetime.datetime( int(access.year), MONTH_ABBR[access.month], int(access.day), int(access.hour), int(access.minute), int(access.second)) # Parse timezone string; "+YYMM" format. entry['utcoffset'] = (1 if access.timezone[0] == '+' else -1) * \ datetime.timedelta(hours=int(access.timezone[1:3]), minutes=int(access.timezone[3:5])) if access.ident != '-': entry['ident'] = access.ident if access.user != '-': entry['user'] = access.user if access.size != '-': entry['size'] = int(access.size) if access.referer != '-': entry['referer'] = access.referer if access.ua != '-': entry['ua'] = access.ua if access.trailing: entry['trailing'] = access.trailing.strip() return entry
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logparse(*args, **kwargs): """ Parse access log on the terminal application. If list of files are given, parse each file. Otherwise, parse standard input. :param args: supporting functions after processed raw log line :type: list of callables :rtype: tuple of (statistics, key/value report) """
from clitool.cli import clistream from clitool.processor import SimpleDictReporter lst = [parse] + args reporter = SimpleDictReporter() stats = clistream(reporter, *lst, **kwargs) return stats, reporter.report()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def std_filter(array, n_std=2.0, return_index=False): """Standard deviation outlier detector. :param array: array of data. :param n_std: default 2.0, exclude data out of ``n_std`` standard deviation. :param return_index: boolean, default False, if True, only returns index. """
if not isinstance(array, np.ndarray): array = np.array(array) mean, std = array.mean(), array.std() good_index = np.where(abs(array - mean) <= n_std * std) bad_index = np.where(abs(array - mean) > n_std * std) if return_index: return good_index[0], bad_index[0] else: return array[good_index], array[bad_index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def box_filter(array, n_iqr=1.5, return_index=False): """Box plot outlier detector. :param array: array of data. :param n_std: default 1.5, exclude data out of ``n_iqr`` IQR. :param return_index: boolean, default False, if True, only returns index. """
if not isinstance(array, np.ndarray): array = np.array(array) Q3 = np.percentile(array, 75) Q1 = np.percentile(array, 25) IQR = Q3 - Q1 lower, upper = Q1 - n_iqr * IQR, Q3 + n_iqr * IQR good_index = np.where(np.logical_and(array >= lower, array <= upper)) bad_index = np.where(np.logical_or(array < lower, array > upper)) if return_index: return good_index[0], bad_index[0] else: return array[good_index], array[bad_index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resize_compute_width_height(fullfile,_megapixels): """Given image file and desired megapixels, computes the new width and height"""
img = Image.open(fullfile) width,height=img.size current_megapixels=width*height/(2.0**20) scale=sqrt(_megapixels/float(current_megapixels)) logger.debug('A resize scale would be %f'%(scale)) # Can't make bigger, return original if scale>= 1.0: logger.warning('Image is %0.1f MP, trying to scale to %0.1f MP - just using original!', current_megapixels,_megapixels); return width,height new_width=int(width*scale) new_height=int(height*scale) return new_width,new_height
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getexif_location(directory,fn): """ directory - Dir where file is located fn - filename to check for EXIF GPS Returns touple of lat,lon if EXIF eg. (34.035460,-118.227885) files contains GPS info, otherwise returns None,None """
lat=None lon=None sign_lat=+1.0 sign_lon=+1.0 # Check if photo as geo info already exif_tags=exifread.process_file(\ open(os.path.join(directory,fn),'rb')) try: d,m,s=exif_tags['GPS GPSLongitude'].values # West is negative longitudes, change sign if exif_tags['GPS GPSLongitudeRef'].values=='W': sign_lon=-1.0 lon=float(d.num) +float(m.num)/60.0 +float(s.num/float(s.den))/3600.0 lon=lon*sign_lon d,m,s=exif_tags['GPS GPSLatitude'].values # South is negative latitude, change sign if exif_tags['GPS GPSLatitudeRef'].values=='S': sign_lat=-1.0 lat=float(d.num)\ +float(m.num)/60.0\ +float(s.num/float(s.den))/3600.0 lat=lat*sign_lat except: logger.debug("%s - Couldn't extract GPS info"%(fn)) return lat,lon