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 initializerepo(self): """ Fill empty directory with products and make first commit """
try: os.mkdir(self.repopath) except OSError: pass cmd = self.repo.init(bare=self.bare, shared=self.shared) if not self.bare: self.write_testing_data([], []) self.write_training_data([], []) self.write_classifier(None) cmd = self.repo.add('training.pkl') cmd = self.repo.add('testing.pkl') cmd = self.repo.add('classifier.pkl') cmd = self.repo.commit(m='initial commit') cmd = self.repo.tag('initial') cmd = self.set_version('initial')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isvalid(self): """ Checks whether contents of repo are consistent with standard set. """
gcontents = [gf.rstrip('\n') for gf in self.repo.bake('ls-files')()] fcontents = os.listdir(self.repopath) return all([sf in gcontents for sf in std_files]) and all([sf in fcontents for sf in std_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 set_version(self, version, force=True): """ Sets the version name for the current state of repo """
if version in self.versions: self._version = version if 'working' in self.repo.branch().stdout: if force: logger.info('Found working branch. Removing...') cmd = self.repo.checkout('master') cmd = self.repo.branch('working', d=True) else: logger.info('Found working branch from previous session. Use force=True to remove it and start anew.') return stdout = self.repo.checkout(version, b='working').stdout # active version set in 'working' branch logger.info('Version {0} set'.format(version)) else: raise AttributeError('Version {0} not found'.format(version))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def training_data(self): """ Returns data dictionary from training.pkl """
data = pickle.load(open(os.path.join(self.repopath, 'training.pkl'))) return data.keys(), data.values()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def classifier(self): """ Returns classifier from classifier.pkl """
clf = pickle.load(open(os.path.join(self.repopath, 'classifier.pkl'))) return clf
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_training_data(self, features, targets): """ Writes data dictionary to filename """
assert len(features) == len(targets) data = dict(zip(features, targets)) with open(os.path.join(self.repopath, 'training.pkl'), 'w') as fp: pickle.dump(data, fp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_classifier(self, clf): """ Writes classifier object to pickle file """
with open(os.path.join(self.repopath, 'classifier.pkl'), 'w') as fp: pickle.dump(clf, fp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit_version(self, version, msg=None): """ Add tag, commit, and push changes """
assert version not in self.versions, 'Will not overwrite a version name.' if not msg: feat, targ = self.training_data msg = 'Training set has {0} examples. '.format(len(feat)) feat, targ = self.testing_data msg += 'Testing set has {0} examples.'.format(len(feat)) cmd = self.repo.commit(m=msg, a=True) cmd = self.repo.tag(version) cmd = self.repo.checkout('master') self.update() cmd = self.repo.merge('working') cmd = self.repo.branch('working', d=True) self.set_version(version) try: stdout = self.repo.push('origin', 'master', '--tags').stdout logger.info(stdout) except: logger.info('Push not working. Remote not defined?')
<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_all_usb_devices(idVendor, idProduct): """ Returns a list of all the usb devices matching the provided vendor ID and product ID."""
all_dev = list(usb.core.find(find_all = True, idVendor = idVendor, idProduct = idProduct)) for dev in all_dev: try: dev.detach_kernel_driver(0) except usb.USBError: pass return all_dev
<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_device_address(usb_device): """ Returns the grizzly's internal address value. Returns a negative error value in case of error. """
try: usb_device.ctrl_transfer(0x21, 0x09, 0x0300, 0, GrizzlyUSB.COMMAND_GET_ADDR) internal_addr = usb_device.ctrl_transfer(0xa1, 0x01, 0x0301, 0, 2)[1] return internal_addr >> 1 except usb.USBError as e: return GrizzlyUSB.USB_DEVICE_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 get_all_ids(idVendor = GrizzlyUSB.ID_VENDOR, idProduct=GrizzlyUSB.ID_PRODUCT): """ Scans for grizzlies that have not been bound, or constructed, and returns a list of their id's, or motor number."""
all_dev = GrizzlyUSB.get_all_usb_devices(idVendor, idProduct) if len(all_dev) <= 0: raise usb.USBError("Could not find any GrizzlyBear device (idVendor=%d, idProduct=%d)" % (idVendor, idProduct)) else: all_addresses = [] # bound devices is a list of devices that are already busy. bound_devices = [] for device in all_dev: internal_addr = GrizzlyUSB.get_device_address(device) if internal_addr == GrizzlyUSB.USB_DEVICE_ERROR: # device bound bound_devices.append(device) else: all_addresses.append(internal_addr) # we release all devices that we aren't using and aren't bound. for device in all_dev: if device not in bound_devices: usb.util.dispose_resources(device) return map(addr_to_id, all_addresses)
<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_register(self, addr, data): """Sets an arbitrary register at @addr and subsequent registers depending on how much data you decide to write. It will automatically fill extra bytes with zeros. You cannot write more than 14 bytes at a time. @addr should be a static constant from the Addr class, e.g. Addr.Speed"""
assert len(data) <= 14, "Cannot write more than 14 bytes at a time" cmd = chr(addr) + chr(len(data) | 0x80) for byte in data: cmd += chr(cast_to_byte(byte)) cmd += (16 - len(cmd)) * chr(0) self._dev.send_bytes(cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_mode(self, controlmode, drivemode): """Higher level abstraction for setting the mode register. This will set the mode according the the @controlmode and @drivemode you specify. @controlmode and @drivemode should come from the ControlMode and DriveMode class respectively."""
self.set_register(Addr.Mode, [0x01 | controlmode | drivemode])
<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_as_int(self, addr, numBytes): """Convenience method. Oftentimes we need to read a range of registers to represent an int. This method will automatically read @numBytes registers starting at @addr and convert the array into an int."""
buf = self.read_register(addr, numBytes) if len(buf) >= 4: return struct.unpack_from("<i", buf)[0] else: rtn = 0 for i, byte in enumerate(buf): rtn |= byte << 8 * i return rtn
<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_as_int(self, addr, val, numBytes = 1): """Convenience method. Oftentimes we need to set a range of registers to represent an int. This method will automatically set @numBytes registers starting at @addr. It will convert the int @val into an array of bytes."""
if not isinstance(val, int): raise ValueError("val must be an int. You provided: %s" % str(val)) buf = [] for i in range(numBytes): buf.append(cast_to_byte(val >> 8 * i)) self.set_register(addr, buf)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_reset(self): """Checks the grizzly to see if it reset itself because of voltage sag or other reasons. Useful to reinitialize acceleration or current limiting."""
currentTime = self._read_as_int(Addr.Uptime, 4) if currentTime <= self._ticks: self._ticks = currentTime return True self._ticks = currentTime 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 limit_current(self, curr): """Sets the current limit on the Grizzly. The units are in amps. The internal default value is 5 amps."""
if curr <= 0: raise ValueError("Current limit must be a positive number. You provided: %s" % str(curr)) current = int(curr * (1024.0 / 5.0) * (66.0 / 1000.0)) self._set_as_int(Addr.CurrentLimit, current, 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 init_pid(self, kp, ki, kd): """Sets the PID constants for the PID modes. Arguments are all floating point numbers."""
p, i, d = map(lambda x: int(x * (2 ** 16)), (kp, ki, kd)) self._set_as_int(Addr.PConstant, p, 4) self._set_as_int(Addr.IConstant, i, 4) self._set_as_int(Addr.DConstant, d, 4)
<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_pid_constants(self): """Reads back the PID constants stored on the Grizzly."""
p = self._read_as_int(Addr.PConstant, 4) i = self._read_as_int(Addr.IConstant, 4) d = self._read_as_int(Addr.DConstant, 4) return map(lambda x: x / (2 ** 16), (p, i, 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 getReposPackageFolder(): """Returns the folder the package is located in."""
libdir = sysconfig.get_python_lib() repodir = os.path.join(libdir, "calcrepo", "repos") return repodir
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replaceNewlines(string, newlineChar): """There's probably a way to do this with string functions but I was lazy. Replace all instances of \r or \n in a string with something else."""
if newlineChar in string: segments = string.split(newlineChar) string = "" for segment in segments: string += segment return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getScriptLocation(): """Helper function to get the location of a Python file."""
location = os.path.abspath("./") if __file__.rfind("/") != -1: location = __file__[:__file__.rfind("/")] return location
<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_param(key, val): """ Parse the query param looking for sparse fields params Ensure the `val` or what will become the sparse fields is always an array. If the query param is not a sparse fields query param then return None. :param key: the query parameter key in the request (left of =) :param val: the query parameter val in the request (right of =) :return: tuple of resource type to implement the sparse fields on & a array of the fields. """
regex = re.compile(r'fields\[([A-Za-z]+)\]') match = regex.match(key) if match: if not isinstance(val, list): val = val.split(',') fields = [field.lower() for field in val] rtype = match.groups()[0].lower() return rtype, fields
<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_param(rtype, fields): """ Ensure the sparse fields exists on the models """
try: # raises ValueError if not found model = rtype_to_model(rtype) model_fields = model.all_fields except ValueError: raise InvalidQueryParams(**{ 'detail': 'The fields query param provided with a ' 'field type of "%s" is unknown.' % rtype, 'links': LINK, 'parameter': PARAM, }) for field in fields: if field not in model_fields: raise InvalidQueryParams(**{ 'detail': 'The fields query param "TYPE" of "%s" ' 'is not possible. It does not have a field ' 'by the name of "%s".' % (rtype, field), 'links': LINK, 'parameter': PARAM, })
<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(req, model): # pylint: disable=unused-argument """ Determine the sparse fields to limit the response to Return a dict where the key is the resource type (rtype) & the value is an array of string fields names to whitelist against. :return: dict """
params = {} for key, val in req.params.items(): try: rtype, fields = _parse_param(key, val) params[rtype] = fields except TypeError: continue if params: _validate_req(req) for rtype, fields in params.items(): _validate_param(rtype, fields) return params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_mxrecords(self): """ Looks up for the MX DNS records of the recipient SMTP server """
import dns.resolver logging.info('Resolving DNS query...') answers = dns.resolver.query(self.domain, 'MX') addresses = [answer.exchange.to_text() for answer in answers] logging.info( '{} records found:\n{}'.format( len(addresses), '\n '.join(addresses))) return addresses
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send(self): """ Attempts the delivery through recipient's domain MX records. """
try: for mx in self.mxrecords: logging.info('Connecting to {} {}...'.format(mx, self.port)) server = smtplib.SMTP(mx, self.port) server.set_debuglevel(logging.root.level < logging.WARN) server.sendmail( self.sender, [self.recipient], self.message.as_string()) server.quit() return True except Exception as e: logging.error(e) if (isinstance(e, IOError) and e.errno in (errno.ENETUNREACH, errno.ECONNREFUSED)): logging.error( 'Please check that port {} is open'.format(self.port)) if logging.root.level < logging.WARN: raise e 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 dispatch(self, requestProtocol, requestPayload): """ Dispatch the request to the appropriate handler. :param requestProtocol: <AbstractApplicationInterfaceProtocol> request protocol :param requestPayload: <dict> request :param version: <float> version :param method: <str> method name :param parameters: <dict> data parameters :return: <void> """
# method decoding method = requestPayload["method"].split(".") if len(method) != 3: requestProtocol.failRequestWithErrors(["InvalidMethod"]) return # parsing method name methodModule = method[0] methodController = method[1] methodAction = method[2] # checking if module exists if not self.application.isModuleLoaded(methodModule): requestProtocol.failRequestWithErrors(["InvalidMethodModule"]) return # checking if controller exists controllerPath = os.path.join( "application", "module", methodModule, "controller", "{}.py".format(methodController) ) if not os.path.isfile(controllerPath): requestProtocol.failRequestWithErrors(["InvalidMethodController"]) return # importing controller controllerSpec = importlib.util.spec_from_file_location( methodController, controllerPath ) controller = importlib.util.module_from_spec(controllerSpec) controllerSpec.loader.exec_module(controller) # instancing controller controllerInstance = controller.Controller( self.application, requestProtocol, requestPayload["version"], requestPayload["parameters"] ) # checking if action exists action = getattr( controllerInstance, "{}Action".format(methodAction), None ) if not callable(action): requestProtocol.failRequestWithErrors(["InvalidMethodAction"]) return # executing action requestProtocol.requestPassedDispatcherValidation() preDispatchAction = getattr(controllerInstance, "preDispatch") postDispatchAction = getattr(controllerInstance, "postDispatch") preDispatchAction() action() postDispatchAction()
<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(self, configuration_folder, args_dict, environment): """Make a temporary configuration file from the files in our folder"""
self.configuration_folder = configuration_folder if not os.path.isdir(configuration_folder): raise BadOption("Specified configuration folder is not a directory!", wanted=configuration_folder) available = [os.path.join(configuration_folder, name) for name in os.listdir(configuration_folder)] available_environments = [os.path.basename(path) for path in available if os.path.isdir(path)] available_environments = [e for e in available_environments if not e.startswith('.')] # Make sure the environment exists if environment and environment not in available_environments: raise BadOption("Specified environment doesn't exist", available=available_environments, wanted=environment) if environment: environment_files = [os.path.join(configuration_folder, "accounts.yaml")] for root, dirs, files in os.walk(os.path.join(configuration_folder, environment)): environment_files.extend(os.path.join(root, filename) for filename in files) with tempfile.NamedTemporaryFile() as fle: contents = json.dumps({"includes": environment_files}) fle.write(contents.encode('utf-8')) fle.flush() args_dict['aws_syncr']['environment'] = os.path.split(environment)[-1] super(Collector, self).prepare(fle.name, args_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 extra_prepare_after_activation(self, configuration, args_dict): """Setup our connection to amazon"""
aws_syncr = configuration['aws_syncr'] configuration["amazon"] = Amazon(configuration['aws_syncr'].environment, configuration['accounts'], debug=aws_syncr.debug, dry_run=aws_syncr.dry_run)
<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_configuration(self, configuration, collect_another_source, done, result, src): """Used to add a file to the configuration, result here is the yaml.load of the src"""
if "includes" in result: for include in result["includes"]: collect_another_source(include) configuration.update(result, source=src)
<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_name_from_class_name(class_name): """ Remove the last 'Template' in the name. """
suffix = 'Template' output = class_name if (class_name.endswith(suffix)): output = class_name[:-len(suffix)] return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_list(): """ Print the list of all available templates. """
term = TerminalView() term.print_info("These are the available templates:") import pkgutil, projy.templates pkgpath = os.path.dirname(projy.templates.__file__) templates = [name for _, name, _ in pkgutil.iter_modules([pkgpath])] for name in templates: # the father of all templates, not a real usable one if (name != 'ProjyTemplate'): term.print_info(term.text_in_color(template_name_from_class_name(name), TERM_PINK))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_info(template): """ Print information about a specific template. """
template.project_name = 'TowelStuff' # fake project name, always the same name = template_name_from_class_name(template.__class__.__name__) term = TerminalView() term.print_info("Content of template {} with an example project " \ "named 'TowelStuff':".format(term.text_in_color(name, TERM_GREEN))) dir_name = None for file_info in sorted(template.files(), key=lambda dir: dir[0]): directory = file_name = template_name = '' if file_info[0]: directory = file_info[0] if file_info[1]: file_name = file_info[1] if file_info[2]: template_name = '\t\t - ' + file_info[2] if (directory != dir_name): term.print_info('\n\t' + term.text_in_color(directory + '/', TERM_PINK)) dir_name = directory term.print_info('\t\t' + term.text_in_color(file_name, TERM_YELLOW) + template_name) # print substitutions try: subs = template.substitutes().keys() if len(subs) > 0: subs.sort() term.print_info("\nSubstitutions of this template are: ") max_len = 0 for key in subs: if max_len < len(key): max_len = len(key) for key in subs: term.print_info(u"\t{0:{1}} -> {2}". format(key, max_len, template.substitutes()[key])) except AttributeError: pass
<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_class_from_name(name): """ Return the template class object from agiven name. """
# import the right template module term = TerminalView() template_name = name + 'Template' try: __import__('projy.templates.' + template_name) template_mod = sys.modules['projy.templates.' + template_name] except ImportError: term.print_error_and_exit("Unable to find {}".format(name)) # import the class from the module try: template_class = getattr(template_mod, template_name) except AttributeError: term.print_error_and_exit("Unable to create a template {}".format(name)) return template_class()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def iteration_length(N, start=0, step=1): '''Return the number of iteration steps over a list of length N, starting at index start, proceeding step elements at a time. ''' if N < 0: raise ValueError('N cannot be negative') if start < 0: start += N if start < 0: raise ValueError('Invalid start value') if step < 0: step = -step new_N = start + 1 if new_N > N: raise ValueError('Invalid parameters') N = new_N start = 0 ret = int(math.ceil((N - start) / float(step))) return max(0, ret)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def run(self, **kwargs): ''' Run all benchmarks. Extras kwargs are passed to benchmarks construtors. ''' self.report_start() for bench in self.benchmarks: bench = bench(before=self.report_before_method, after=self.report_after_method, after_each=self.report_progress, debug=self.debug, **kwargs) self.report_before_class(bench) bench.run() self.report_after_class(bench) self.runned.append(bench) self.report_end()
<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_module(self, filename): '''Load a benchmark module from file''' if not isinstance(filename, string_types): return filename basename = os.path.splitext(os.path.basename(filename))[0] basename = basename.replace('.bench', '') modulename = 'benchmarks.{0}'.format(basename) return load_module(modulename, 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 load_from_module(self, module): '''Load all benchmarks from a given module''' benchmarks = [] for name in dir(module): obj = getattr(module, name) if (inspect.isclass(obj) and issubclass(obj, Benchmark) and obj != Benchmark): benchmarks.append(obj) return benchmarks
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boundingBox(booleanArray): """ return indices of the smallest bounding box enclosing all non-zero values within an array (slice(1, 3, None), slice(0, 3, None)) """
w = np.where(booleanArray) p = [] for i in w: if len(i): p.append(slice(i.min(), i.max())) else: p.append(slice(0, 0)) # return None return tuple(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 FromMessageGetSimpleElementDeclaration(message): '''If message consists of one part with an element attribute, and this element is a simpleType return a string representing the python type, else return None. ''' assert isinstance(message, WSDLTools.Message), 'expecting WSDLTools.Message' if len(message.parts) == 1 and message.parts[0].element is not None: part = message.parts[0] nsuri,name = part.element wsdl = message.getWSDL() types = wsdl.types if types.has_key(nsuri) and types[nsuri].elements.has_key(name): e = types[nsuri].elements[name] if isinstance(e, XMLSchema.ElementDeclaration) is True and e.getAttribute('type'): typ = e.getAttribute('type') bt = BaseTypeInterpreter() ptype = bt.get_pythontype(typ[1], typ[0]) return ptype 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 getAttributeName(self, name): '''represents the aname ''' if self.func_aname is None: return name assert callable(self.func_aname), \ 'expecting callable method for attribute func_aname, not %s' %type(self.func_aname) f = self.func_aname return f(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 getPyClass(self): '''Name of generated inner class that will be specified as pyclass. ''' # --> EXTENDED if self.hasExtPyClass(): classInfo = self.extPyClasses[self.name] return ".".join(classInfo) # <-- return 'Holder'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getPyClassDefinition(self): '''Return a list containing pyclass definition. ''' kw = KW.copy() # --> EXTENDED if self.hasExtPyClass(): classInfo = self.extPyClasses[self.name] kw['classInfo'] = classInfo[0] return ["%(ID3)simport %(classInfo)s" %kw ] # <-- kw['pyclass'] = self.getPyClass() definition = [] definition.append('%(ID3)sclass %(pyclass)s:' %kw) if self.metaclass is not None: kw['type'] = self.metaclass definition.append('%(ID4)s__metaclass__ = %(type)s' %kw) definition.append('%(ID4)stypecode = self' %kw) #TODO: Remove pyclass holder __init__ --> definition.append('%(ID4)sdef __init__(self):' %kw) definition.append('%(ID5)s# pyclass' %kw) # JRB HACK need to call _setElements via getElements self._setUpElements() # JRB HACK need to indent additional one level for el in self.elementAttrs: kw['element'] = el definition.append('%(ID2)s%(element)s' %kw) definition.append('%(ID5)sreturn' %kw) # <-- # pyclass descriptive name if self.name is not None: kw['name'] = self.name definition.append(\ '%(ID3)s%(pyclass)s.__name__ = "%(name)s_Holder"' %kw ) return definition
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nsuriLogic(self): '''set a variable "ns" that represents the targetNamespace in which this item is defined. Used for namespacing local elements. ''' if self.parentClass: return 'ns = %s.%s.schema' %(self.parentClass, self.getClassName()) return 'ns = %s.%s.schema' %(self.getNSAlias(), self.getClassName())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _getOccurs(self, e): '''return a 3 item tuple ''' minOccurs = maxOccurs = '1' nillable = True return minOccurs,maxOccurs,nillable
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getAttributeNames(self): '''returns a list of anames representing the parts of the message. ''' return map(lambda e: self.getAttributeName(e.name), self.tcListElements)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _setContent(self): '''GED defines element name, so also define typecode aname ''' kw = KW.copy() try: kw.update(dict(klass=self.getClassName(), element='ElementDeclaration', literal=self.literalTag(), substitutionGroup=self._substitutionGroupTag(), schema=self.schemaTag(), init=self.simpleConstructor(), ns=self.ns, name=self.name, aname=self.getAttributeName(self.name), baseslogic=self.getBasesLogic(ID3), #ofwhat=self.getTypecodeList(), #atypecode=self.attribute_typecode, #pyclass=self.getPyClass(), alias=NAD.getAlias(self.sKlassNS), subclass=type_class_name(self.sKlass), )) except Exception, ex: args = ['Failure processing an element w/local complexType: %s' %( self._item.getItemTrace())] args += ex.args ex.args = tuple(args) raise if self.local: kw['element'] = 'LocalElementDeclaration' element = [ '%(ID1)sclass %(klass)s(%(element)s):', '%(ID2)s%(literal)s', '%(ID2)s%(schema)s', '%(ID2)s%(substitutionGroup)s', '%(ID2)s%(init)s', '%(ID3)skw["pname"] = ("%(ns)s","%(name)s")', '%(ID3)skw["aname"] = "%(aname)s"', '%(baseslogic)s', '%(ID3)s%(alias)s.%(subclass)s.__init__(self, **kw)', '%(ID3)sif self.pyclass is not None: self.pyclass.__name__ = "%(klass)s_Holder"', ] self.writeArray(map(lambda l: l %kw, element))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situations like GH #1225 where Django may not have resolved a string-based reference to a model in another model's foreign key definition. String representations should have the format: 'appname.ModelName' """
if isinstance(obj, six.string_types) and len(obj.split('.')) == 2: app_name, model_name = obj.split('.') resolved_model = apps.get_model(app_name, model_name) if resolved_model is None: msg = "Django did not return a model for {0}.{1}" raise ImproperlyConfigured(msg.format(app_name, model_name)) return resolved_model elif inspect.isclass(obj) and issubclass(obj, models.Model): return obj raise ValueError("{0} is not a Django model".format(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 is_abstract_model(model): """ Given a model class, returns a boolean True if it is abstract and False if it is not. """
return hasattr(model, '_meta') and hasattr(model._meta, 'abstract') and model._meta.abstract
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Queues all services to be polled. Should be run via beat. """
services = Service.objects.all() for service in services: poll_service.apply_async(kwargs={"service_id": str(service.id)}) return "Queued <%s> Service(s) for Polling" % services.count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, service_id, user_id, email, **kwargs): """ Create and Retrieve a token from remote service. Save to DB. """
log = self.get_logger(**kwargs) log.info("Loading Service for token creation") try: service = Service.objects.get(id=service_id) log.info("Getting token for <%s> on <%s>" % (email, service.name)) response = self.create_token(service.url, email, service.token) try: result = response.json() ust, created = UserServiceToken.objects.get_or_create( service=service, user_id=user_id, email=email) ust.token = result["token"] ust.save() log.info( "Token saved for <%s> on <%s>" % (email, service.name)) except Exception: # can't decode means there was not a valid response log.info("Failed to parse response from <%s>" % (service.name)) return "Completed getting token for <%s>" % (email) except ObjectDoesNotExist: logger.error('Missing Service', exc_info=True) except SoftTimeLimitExceeded: logger.error( 'Soft time limit exceed processing getting service token \ via Celery.', exc_info=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 run(self): """ Queues all services to be polled for metrics. Should be run via beat. """
services = Service.objects.all() for service in services: service_metric_sync.apply_async( kwargs={"service_id": str(service.id)}) key = "services.downtime.%s.sum" % ( utils.normalise_string(service.name)) check = WidgetData.objects.filter(service=None, key=key) if not check.exists(): WidgetData.objects.create( key=key, title="TEMP - Pending update" ) return "Queued <%s> Service(s) for Metric Sync" % services.count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, service_id, **kwargs): """ Retrieve a list of metrics. Ensure they are set as metric data sources. """
log = self.get_logger(**kwargs) log.info("Loading Service for metric sync") try: service = Service.objects.get(id=service_id) log.info("Getting metrics for <%s>" % (service.name)) metrics = self.get_metrics(service.url, service.token) result = metrics.json() if "metrics_available" in result: for key in result["metrics_available"]: check = WidgetData.objects.filter(service=service, key=key) if not check.exists(): WidgetData.objects.create( service=service, key=key, title="TEMP - Pending update" ) log.info("Add WidgetData for <%s>" % (key,)) return "Completed metric sync for <%s>" % (service.name) except ObjectDoesNotExist: logger.error('Missing Service', exc_info=True) except SoftTimeLimitExceeded: logger.error( 'Soft time limit exceed processing pull of service metrics \ via Celery.', exc_info=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 end_timing(self): """ Ends timing of an execution block, calculates elapsed time and updates the associated counter. """
if self._callback != None: elapsed = time.perf_counter() * 1000 - self._start self._callback.end_timing(self._counter, elapsed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prune_directory(self): """Delete any objects that can be loaded and are expired according to the current lifetime setting. A file will be deleted if the following conditions are met: - The file extension matches :py:meth:`bucketcache.backends.Backend.file_extension` - The object can be loaded by the configured backend. - The object's expiration date has passed. Returns: File size and number of files deleted. :rtype: :py:class:`~bucketcache.utilities.PrunedFilesInfo` .. note:: For any buckets that share directories, ``prune_directory`` will affect files saved with both, if they use the same backend class. This is not destructive, because only files that have expired according to the lifetime of the original bucket are deleted. """
glob = '*.{ext}'.format(ext=self.backend.file_extension) totalsize = 0 totalnum = 0 for f in self._path.glob(glob): filesize = f.stat().st_size key_hash = f.stem in_cache = key_hash in self._cache try: self._get_obj_from_hash(key_hash) except KeyExpirationError: # File has been deleted by `_get_obj_from_hash` totalsize += filesize totalnum += 1 except KeyInvalidError: pass except Exception: raise else: if not in_cache: del self._cache[key_hash] return PrunedFilesInfo(size=totalsize, num=totalnum)
<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(self): """Commit deferred writes to file."""
for key_hash, obj in six.iteritems(self._cache): # Objects are checked for expiration in __getitem__, # but we can check here to avoid unnecessary writes. if not obj.has_expired(): file_path = self._path_for_hash(key_hash) with open(str(file_path), self._write_mode) as f: obj.dump(f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_url(self, resource, params=None): """ Generate url for request """
# replace placeholders pattern = r'\{(.+?)\}' resource = re.sub(pattern, lambda t: str(params.get(t.group(1), '')), resource) # build url parts = (self.endpoint, '/api/', resource) return '/'.join(map(lambda x: str(x).strip('/'), parts))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, method, resource, params=None): """ Make request to the server and parse response """
url = self.get_url(resource, params) # headers headers = { 'Content-Type': 'application/json' } auth = requests.auth.HTTPBasicAuth(self.username, self.password) # request log.info('Request to %s. Data: %s' % (url, params)) response = requests.request(method, url, data=json.dumps(params), headers=headers, auth=auth) response.raise_for_status() # response log.info('Response from %s: %s' % (url, response.text)) content = response.json() self.parse_status(content.get('status')) 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 modify_attached_policies(self, role_name, new_policies): """Make sure this role has just the new policies"""
parts = role_name.split('/', 1) if len(parts) == 2: prefix, name = parts prefix = "/{0}/".format(prefix) else: prefix = "/" name = parts[0] current_attached_policies = [] with self.ignore_missing(): current_attached_policies = self.client.list_attached_role_policies(RoleName=name) current_attached_policies = [p['PolicyArn'] for p in current_attached_policies["AttachedPolicies"]] new_attached_policies = ["arn:aws:iam::aws:policy/{0}".format(p) for p in new_policies] changes = list(Differ.compare_two_documents(current_attached_policies, new_attached_policies)) if changes: with self.catch_boto_400("Couldn't modify attached policies", role=role_name): for policy in new_attached_policies: if policy not in current_attached_policies: for _ in self.change("+", "attached_policy", role=role_name, policy=policy): self.client.attach_role_policy(RoleName=name, PolicyArn=policy) for policy in current_attached_policies: if policy not in new_attached_policies: for _ in self.change("-", "attached_policy", role=role_name, changes=changes, policy=policy): self.client.detach_role_policy(RoleName=name, PolicyArn=policy)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assume_role_credentials(self, arn): """Return the environment variables for an assumed role"""
log.info("Assuming role as %s", arn) # Clear out empty values for name in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN']: if name in os.environ and not os.environ[name]: del os.environ[name] sts = self.amazon.session.client("sts") with self.catch_boto_400("Couldn't assume role", arn=arn): creds = sts.assume_role(RoleArn=arn, RoleSessionName="aws_syncr") return { 'AWS_ACCESS_KEY_ID': creds["Credentials"]["AccessKeyId"] , 'AWS_SECRET_ACCESS_KEY': creds["Credentials"]["SecretAccessKey"] , 'AWS_SECURITY_TOKEN': creds["Credentials"]["SessionToken"] , 'AWS_SESSION_TOKEN': creds["Credentials"]["SessionToken"] }
<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_token(self): ''' a method to validate active access token ''' title = '%s._validate_token' % self.__class__.__name__ # construct access token url import requests url = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' % self.access_token # retrieve access token details try: token_details = requests.get(url).json() except: raise DriveConnectionError(title) if 'error' in token_details.keys(): raise ValueError('access_token for google drive account is %s' % token_details['error_description']) # determine collection space # https://developers.google.com/drive/v3/web/about-organization if 'scope' in token_details.keys(): service_scope = token_details['scope'] if service_scope.find('drive.appfolder') > -1: self.drive_space = 'appDataFolder' if not self.collection_name: self.collection_name = 'App Data Folder' elif service_scope.find('drive.photos.readonly') > -1: self.drive_space = 'photos' if not self.collection_name: self.collection_name = 'Photos' # determine permissions # https://developers.google.com/drive/v3/web/about-auth if service_scope.find('readonly') > -1: self.permissions_write = False if service_scope.find('readonly.metadata') > -1: self.permissions_content = False # TODO refresh token if 'expires_in' in token_details.keys(): from time import time expiration_date = time() + token_details['expires_in'] if 'issued_to' in token_details.keys(): client_id = token_details['issued_to'] return token_details
<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_id(self, file_path): ''' a helper method for retrieving id of file or folder ''' title = '%s._get_id' % self.__class__.__name__ # construct request kwargs list_kwargs = { 'spaces': self.drive_space, 'fields': 'files(id, parents)' } # determine path segments path_segments = file_path.split(os.sep) # walk down parents to file name parent_id = '' empty_string = '' while path_segments: walk_query = "name = '%s'" % path_segments.pop(0) if parent_id: walk_query += "and '%s' in parents" % parent_id list_kwargs['q'] = walk_query try: response = self.drive.list(**list_kwargs).execute() except: raise DriveConnectionError(title) file_list = response.get('files', []) if file_list: if path_segments: parent_id = file_list[0].get('id') else: file_id = file_list[0].get('id') return file_id, parent_id else: return empty_string, empty_string
<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_space(self): ''' a helper method to retrieve id of drive space ''' title = '%s._space_id' % self.__class__.__name__ list_kwargs = { 'q': "'%s' in parents" % self.drive_space, 'spaces': self.drive_space, 'fields': 'files(name, parents)', 'pageSize': 1 } try: response = self.drive.list(**list_kwargs).execute() except: raise DriveConnectionError(title) for file in response.get('files',[]): self.space_id = file.get('parents')[0] break return self.space_id
<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_data(self, file_id): ''' a helper method for retrieving the byte data of a file ''' title = '%s._get_data' % self.__class__.__name__ # request file data try: record_data = self.drive.get_media(fileId=file_id).execute() except: raise DriveConnectionError(title) return record_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 _get_metadata(self, file_id, metadata_fields=''): ''' a helper method for retrieving the metadata of a file ''' title = '%s._get_metadata' % self.__class__.__name__ # construct fields arg if not metadata_fields: metadata_fields = ','.join(self.object_file.keys()) else: field_list = metadata_fields.split(',') for field in field_list: if not field in self.object_file.keys(): raise ValueError('%s(metadata_fields="%s") is not a valid drive file field' % (title, field)) # send request try: metadata_details = self.drive.get(fileId=file_id, fields=metadata_fields).execute() except: raise DriveConnectionError(title) return metadata_details
<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_directory(self, folder_id=''): ''' a generator method for listing the contents of a directory ''' title = '%s._list_directory' % self.__class__.__name__ # construct default response file_list = [] # construct request kwargs list_kwargs = { 'spaces': self.drive_space, 'fields': 'nextPageToken, files(id, name, parents, mimeType)' } # add query field for parent if folder_id: list_kwargs['q'] = "'%s' in parents" % folder_id # retrieve space id if not self.space_id: self._get_space() # send request page_token = 1 while page_token: try: response = self.drive.list(**list_kwargs).execute() except: raise DriveConnectionError(title) # populate list from response results = response.get('files', []) for file in results: if not folder_id and file.get('parents', [])[0] != self.space_id: pass else: yield file.get('id', ''), file.get('name', ''), file.get('mimeType', '') # get page token page_token = response.get('nextPageToken', None) if page_token: list_kwargs['pageToken'] = page_token return file_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 _walk(self, root_path='', root_id=''): ''' a generator method which walks the file structure of the dropbox collection ''' title = '%s._walk' % self.__class__.__name__ if root_id: pass elif root_path: root_id, root_parent = self._get_id(root_path) for file_id, name, mimetype in self._list_directory(root_id): file_path = os.path.join(root_path, name) if mimetype == 'application/vnd.google-apps.folder': for path, id in self._walk(root_path=file_path, root_id=file_id): yield path, id else: yield file_path, file_id
<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(self, record_key, secret_key=''): ''' a method to retrieve byte data of appdata record :param record_key: string with name of record :param secret_key: [optional] string used to decrypt data :return: byte data for record body ''' title = '%s.load' % self.__class__.__name__ # validate inputs input_fields = { 'record_key': record_key, 'secret_key': secret_key } for key, value in input_fields.items(): if value: object_title = '%s(%s=%s)' % (title, key, str(value)) self.fields.validate(value, '.%s' % key, object_title) # verify permissions if not self.permissions_content: raise Exception('%s requires an access_token with file content permissions.' % title) # retrieve file id file_id, parent_id = self._get_id(record_key) if not file_id: raise Exception('%s(record_key=%s) does not exist.' % (title, record_key)) # request file data try: record_data = self.drive.get_media(fileId=file_id).execute() except: raise DriveConnectionError(title) # retrieve data from response # import io # from googleapiclient.http import MediaIoBaseDownload # file_header = io.BytesIO # record_data = MediaIoBaseDownload(file_header, response) # done = False # while not done: # status, done = record_data.next_chunk() # TODO export google document to other format # decrypt (if necessary) if secret_key: from labpack.encryption import cryptolab record_data = cryptolab.decrypt(record_data, secret_key) return record_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 list(self, prefix='', delimiter='', filter_function=None, max_results=1, previous_key=''): ''' a method to list keys in the google drive collection :param prefix: string with prefix value to filter results :param delimiter: string with value which results must not contain (after prefix) :param filter_function: (positional arguments) function used to filter results :param max_results: integer with maximum number of results to return :param previous_key: string with key in collection to begin search after :return: list of key strings NOTE: each key string can be divided into one or more segments based upon the / characters which occur in the key string as well as its file extension type. if the key string represents a file path, then each directory in the path, the file name and the file extension are all separate indexed values. eg. lab/unittests/1473719695.2165067.json is indexed: [ 'lab', 'unittests', '1473719695.2165067', '.json' ] it is possible to filter the records in the collection according to one or more of these path segments using a filter_function. NOTE: the filter_function must be able to accept an array of positional arguments and return a value that can evaluate to true or false. while searching the records, list produces an array of strings which represent the directory structure in relative path of each key string. if a filter_function is provided, this list of strings is fed to the filter function. if the function evaluates this input and returns a true value the file will be included in the list results. ''' title = '%s.list' % self.__class__.__name__ # validate input input_fields = { 'prefix': prefix, 'delimiter': delimiter, 'max_results': max_results, 'previous_key': previous_key } for key, value in input_fields.items(): if value: object_title = '%s(%s=%s)' % (title, key, str(value)) self.fields.validate(value, '.%s' % key, object_title) # validate filter function if filter_function: try: path_segments = [ 'lab', 'unittests', '1473719695.2165067', '.json' ] filter_function(*path_segments) except: err_msg = '%s(filter_function=%s)' % (title, filter_function.__class__.__name__) raise TypeError('%s must accept positional arguments.' % err_msg) # construct empty results list results_list = [] check_key = True if previous_key: check_key = False # determine root path root_path = '' if prefix: from os import path root_path, file_name = path.split(prefix) # iterate over dropbox files for file_path, file_id in self._walk(root_path): path_segments = file_path.split(os.sep) record_key = os.path.join(*path_segments) record_key = record_key.replace('\\','/') if record_key == previous_key: check_key = True # find starting point if not check_key: continue # apply prefix filter partial_key = record_key if prefix: if record_key.find(prefix) == 0: partial_key = record_key[len(prefix):] else: continue # apply delimiter filter if delimiter: if partial_key.find(delimiter) > -1: continue # apply filter function if filter_function: if filter_function(*path_segments): results_list.append(record_key) else: results_list.append(record_key) # return results list if len(results_list) == max_results: return results_list return results_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 delete(self, record_key): ''' a method to delete a file :param record_key: string with name of file :return: string reporting outcome ''' title = '%s.delete' % self.__class__.__name__ # validate inputs input_fields = { 'record_key': record_key } for key, value in input_fields.items(): object_title = '%s(%s=%s)' % (title, key, str(value)) self.fields.validate(value, '.%s' % key, object_title) # validate existence of file file_id, parent_id = self._get_id(record_key) if not file_id: exit_msg = '%s does not exist.' % record_key return exit_msg # remove file try: self.drive.delete(fileId=file_id).execute() except: raise DriveConnectionError(title) # determine file directory current_dir = os.path.split(record_key)[0] # remove empty parent folders try: while current_dir: folder_id, parent_id = self._get_id(current_dir) count = 0 for id, name, mimetype in self._list_directory(folder_id): count += 1 break if count: self.drive.delete(fileId=folder_id).execute() current_dir = os.path.split(current_dir)[0] else: break except: raise DriveConnectionError(title) # return exit message exit_msg = '%s has been deleted.' % record_key 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 remove(self): ''' a method to remove all records in the collection NOTE: this method removes all the files in the collection, but the collection folder itself created by oauth2 cannot be removed. only the user can remove access to the app folder :return: string with confirmation of deletion ''' title = '%s.remove' % self.__class__.__name__ # get contents of root for id, name, mimetype in self._list_directory(): try: self.drive.delete(fileId=id).execute() except Exception as err: if str(err).find('File not found') > -1: pass else: raise DriveConnectionError(title) # return outcome insert = 'collection' if self.collection_name: insert = self.collection_name exit_msg = 'Contents of %s will be removed from Google Drive.' % insert 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 read_message(self): """Try to read a message from the buffered data. A message is defined as a 32-bit integer size, followed that number of bytes. First we try to non-destructively read the integer. Then, we try to non- destructively read the remaining bytes. If both are successful, we then go back to remove the span from the front of the buffers. """
with self.__class__.__locker: result = self.__passive_read(4) if result is None: return None (four_bytes, last_buffer_index, updates1) = result (length,) = unpack('>I', four_bytes) result = self.__passive_read(length, last_buffer_index) if result is None: return None (data, last_buffer_index, updates2) = result # If we get here, we found a message. Remove it from the buffers. for updates in (updates1, updates2): for update in updates: (buffer_index, buffer_, length_consumed) = update self.__buffers[buffer_index] = buffer_ if buffer_ else '' self.__length -= length_consumed self.__read_buffer_index = last_buffer_index self.__hits += 1 if self.__hits >= self.__class__.__cleanup_interval: self.__cleanup() self.__hits = 0 return 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 __cleanup(self): """Clip buffers that the top of our list that have been completely exhausted. """
# TODO: Test this. with self.__class__.__locker: while self.__read_buffer_index > 0: del self.__buffers[0] self.__read_buffer_index -= 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 ls(dataset_uri): """ List the overlays in the dataset. """
dataset = dtoolcore.DataSet.from_uri(dataset_uri) for overlay_name in dataset.list_overlay_names(): click.secho(overlay_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 show(dataset_uri, overlay_name): """ Show the content of a specific overlay. """
dataset = dtoolcore.DataSet.from_uri(dataset_uri) try: overlay = dataset.get_overlay(overlay_name) except: # NOQA click.secho( "No such overlay: {}".format(overlay_name), fg="red", err=True ) sys.exit(11) formatted_json = json.dumps(overlay, indent=2) colorful_json = pygments.highlight( formatted_json, pygments.lexers.JsonLexer(), pygments.formatters.TerminalFormatter()) click.secho(colorful_json, nl=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 canonicalize_header(key): """Returns the canonicalized header name for the header name provided as an argument. The canonicalized header name according to the HTTP RFC is Kebab-Camel-Case. Keyword arguments: key -- the name of the header """
bits = key.split('-') for idx, b in enumerate(bits): bits[idx] = b.capitalize() return '-'.join(bits)
<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(self): """Validates the URL object. The URL object is invalid if it does not represent an absolute URL. Returns True or False based on this. """
if (self.scheme is None or self.scheme != '') \ and (self.host is None or self.host == ''): 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 request_uri(self): """Returns the request URL element of the URL. This request URL is the path, the query and the fragment appended as a relative URL to the host. The request URL always contains at least a leading slash. """
result = '/{0}'.format(self.path.lstrip('/')) if self.query is not None and self.query != '' and self.query != {}: result += '?{0}'.format(self.encoded_query()) if self.fragment is not None and self.fragment != '': result += '#{0}'.format(self.fragment) 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 encoded_query(self): """Returns the encoded query string of the URL. This may be different from the rawquery element, as that contains the query parsed by urllib but unmodified. The return value takes the form of key=value&key=value, and it never contains a leading question mark. """
if self.query is not None and self.query != '' and self.query != {}: try: return urlencode(self.query, doseq=True, quote_via=urlquote) except TypeError: return '&'.join(["{0}={1}".format(urlquote(k), urlquote(self.query[k][0])) for k in self.query]) else: 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 with_url(self, url): """Sets the request's URL and returns the request itself. Automatically sets the Host header according to the URL. Keyword arguments: url -- a string representing the URL the set for the request """
self.url = URL(url) self.header["Host"] = self.url.host 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 with_headers(self, headers): """Sets multiple headers on the request and returns the request itself. Keyword arguments: headers -- a dict-like object which contains the headers to set. """
for key, value in headers.items(): self.with_header(key, value) 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 with_body(self, body): # @todo take encoding into account """Sets the request body to the provided value and returns the request itself. Keyword arguments: body -- A UTF-8 string or bytes-like object which represents the request body. """
try: self.body = body.encode('utf-8') except: try: self.body = bytes(body) except: raise ValueError("Request body must be a string or bytes-like object.") hasher = hashlib.sha256() hasher.update(self.body) digest = base64.b64encode(hasher.digest()).decode('utf-8') self.with_header("X-Authorization-Content-Sha256", digest) 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 get_header(self, key): """Returns the requested header, or an empty string if the header is not set. Keyword arguments: key -- The header name. It will be canonicalized before use. """
key = canonicalize_header(key) if key in self.header: return self.header[key] 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 do(self): """Executes the request represented by this object. The requests library will be used for this purpose. Returns an instance of requests.Response. """
data = None if self.body is not None and self.body != b'': data = self.body return requests.request(self.method, str(self.url), data=data, headers=self.header)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setWriteToShell(self, writeToShell=True): """connect sysout to the qtSignal"""
if writeToShell and not self._connected: self.message.connect(self.stdW) self._connected = True elif not writeToShell and self._connected: try: self.message.disconnect(self.stdW) except TypeError: pass # was not connected self._connected = 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 _get_app(self, appname): """ returns app object or None """
try: app = APPS.get_app_config(appname) except Exception as e: self.err(e) return return app
<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_model(self, appname, modelname): """ return model or None """
app = self._get_app(appname) models = app.get_models() model = None for mod in models: if mod.__name__ == modelname: model = mod return model msg = "Model " + modelname + " not found"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _count_model(self, model): """ return model count """
try: res = model.objects.all().count() except Exception as e: self.err(e) return 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 find_setup_file_name(self): # type: () ->None """ Usually setup.py or setup """
for file_path in [ x for x in os.listdir(".") if os.path.isfile(x) and x in ["setup.py", "setup"] ]: if self.file_opener.is_python_inside(file_path): self.setup_file_name = file_path break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clause_tokenize(sentence): """ Split on comma or parenthesis, if there are more then three words for each clause ['While I was walking home,', ' this bird fell down in front of me.'] """
clause_re = re.compile(r'((?:\S+\s){2,}\S+,|(?:\S+\s){3,}(?=\((?:\S+\s){2,}\S+\)))') clause_stem = clause_re.sub(r'\1###clausebreak###', sentence) return [c for c in clause_stem.split('###clausebreak###') if 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 word_tokenize(sentence): """ A generator which yields tokens based on the given sentence without deleting anything. ['I', ' ', 'love', ' ', 'you', '.', ' ', 'Please', ' ', 'don', "'", 't', ' ', 'leave', '.'] """
date_pattern = r'\d\d(\d\d)?[\\-]\d\d[\\-]\d\d(\d\d)?' number_pattern = r'[\+-]?(\d+\.\d+|\d{1,3},(\d{3},)*\d{3}|\d+)' arr_pattern = r'(?: \w\.){2,3}|(?:\A|\s)(?:\w\.){2,3}|[A-Z]\. [a-z]' word_pattern = r'[\w]+' non_space_pattern = r'[{}]|\w'.format(re.escape('!"#$%&()*,./:;<=>?@[\]^_-`{|}~')) space_pattern = r'\s' anything_pattern = r'.' patterns = [date_pattern, number_pattern, arr_pattern, word_pattern, non_space_pattern, space_pattern, anything_pattern] big_pattern = r'|'.join([('(' + pattern + ')') for pattern in patterns]) for match in re.finditer(big_pattern, sentence): yield match.group(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 slim_stem(token): """ A very simple stemmer, for entity of GO stemming. 'interact' """
target_sulfixs = ['ic', 'tic', 'e', 'ive', 'ing', 'ical', 'nal', 'al', 'ism', 'ion', 'ation', 'ar', 'sis', 'us', 'ment'] for sulfix in sorted(target_sulfixs, key=len, reverse=True): if token.endswith(sulfix): token = token[0:-len(sulfix)] break if token.endswith('ll'): token = token[:-1] return token
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ngram(n, iter_tokens): """ Return a generator of n-gram from an iterable """
z = len(iter_tokens) return (iter_tokens[i:i+n] for i in range(z-n+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 set_overcloud_passwords(self, parameters, parsed_args): """Add passwords to the parameters dictionary :param parameters: A dictionary for the passwords to be added to :type parameters: dict """
undercloud_ceilometer_snmpd_password = utils.get_config_value( "auth", "undercloud_ceilometer_snmpd_password") self.passwords = passwords = utils.generate_overcloud_passwords() ceilometer_pass = passwords['OVERCLOUD_CEILOMETER_PASSWORD'] ceilometer_secret = passwords['OVERCLOUD_CEILOMETER_SECRET'] if parsed_args.templates: parameters['AdminPassword'] = passwords['OVERCLOUD_ADMIN_PASSWORD'] parameters['AdminToken'] = passwords['OVERCLOUD_ADMIN_TOKEN'] parameters['CeilometerPassword'] = ceilometer_pass parameters['CeilometerMeteringSecret'] = ceilometer_secret parameters['CinderPassword'] = passwords[ 'OVERCLOUD_CINDER_PASSWORD'] parameters['GlancePassword'] = passwords[ 'OVERCLOUD_GLANCE_PASSWORD'] parameters['HeatPassword'] = passwords['OVERCLOUD_HEAT_PASSWORD'] parameters['HeatStackDomainAdminPassword'] = passwords[ 'OVERCLOUD_HEAT_STACK_DOMAIN_PASSWORD'] parameters['NeutronPassword'] = passwords[ 'OVERCLOUD_NEUTRON_PASSWORD'] parameters['NovaPassword'] = passwords['OVERCLOUD_NOVA_PASSWORD'] parameters['SwiftHashSuffix'] = passwords['OVERCLOUD_SWIFT_HASH'] parameters['SwiftPassword'] = passwords['OVERCLOUD_SWIFT_PASSWORD'] parameters['SnmpdReadonlyUserPassword'] = ( undercloud_ceilometer_snmpd_password) else: parameters['Controller-1::AdminPassword'] = passwords[ 'OVERCLOUD_ADMIN_PASSWORD'] parameters['Controller-1::AdminToken'] = passwords[ 'OVERCLOUD_ADMIN_TOKEN'] parameters['Compute-1::AdminPassword'] = passwords[ 'OVERCLOUD_ADMIN_PASSWORD'] parameters['Controller-1::SnmpdReadonlyUserPassword'] = ( undercloud_ceilometer_snmpd_password) parameters['Cinder-Storage-1::SnmpdReadonlyUserPassword'] = ( undercloud_ceilometer_snmpd_password) parameters['Swift-Storage-1::SnmpdReadonlyUserPassword'] = ( undercloud_ceilometer_snmpd_password) parameters['Compute-1::SnmpdReadonlyUserPassword'] = ( undercloud_ceilometer_snmpd_password) parameters['Controller-1::CeilometerPassword'] = ceilometer_pass parameters[ 'Controller-1::CeilometerMeteringSecret'] = ceilometer_secret parameters['Compute-1::CeilometerPassword'] = ceilometer_pass parameters[ 'Compute-1::CeilometerMeteringSecret'] = ceilometer_secret parameters['Controller-1::CinderPassword'] = ( passwords['OVERCLOUD_CINDER_PASSWORD']) parameters['Controller-1::GlancePassword'] = ( passwords['OVERCLOUD_GLANCE_PASSWORD']) parameters['Controller-1::HeatPassword'] = ( passwords['OVERCLOUD_HEAT_PASSWORD']) parameters['Controller-1::HeatStackDomainAdminPassword'] = ( passwords['OVERCLOUD_HEAT_STACK_DOMAIN_PASSWORD']) parameters['Controller-1::NeutronPassword'] = ( passwords['OVERCLOUD_NEUTRON_PASSWORD']) parameters['Compute-1::NeutronPassword'] = ( passwords['OVERCLOUD_NEUTRON_PASSWORD']) parameters['Controller-1::NovaPassword'] = ( passwords['OVERCLOUD_NOVA_PASSWORD']) parameters['Compute-1::NovaPassword'] = ( passwords['OVERCLOUD_NOVA_PASSWORD']) parameters['Controller-1::SwiftHashSuffix'] = ( passwords['OVERCLOUD_SWIFT_HASH']) parameters['Controller-1::SwiftPassword'] = ( passwords['OVERCLOUD_SWIFT_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 _get_stack(self, orchestration_client, stack_name): """Get the ID for the current deployed overcloud stack if it exists."""
try: stack = orchestration_client.stacks.get(stack_name) self.log.info("Stack found, will be doing a stack update") return stack except HTTPNotFound: self.log.info("No stack found, will be doing a stack create")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _heat_deploy(self, stack, stack_name, template_path, parameters, environments, timeout): """Verify the Baremetal nodes are available and do a stack update"""
self.log.debug("Processing environment files") env_files, env = ( template_utils.process_multiple_environments_and_files( environments)) self.log.debug("Getting template contents") template_files, template = template_utils.get_template_contents( template_path) files = dict(list(template_files.items()) + list(env_files.items())) clients = self.app.client_manager orchestration_client = clients.rdomanager_oscplugin.orchestration() self.log.debug("Deploying stack: %s", stack_name) self.log.debug("Deploying template: %s", template) self.log.debug("Deploying parameters: %s", parameters) self.log.debug("Deploying environment: %s", env) self.log.debug("Deploying files: %s", files) stack_args = { 'stack_name': stack_name, 'template': template, 'parameters': parameters, 'environment': env, 'files': files } if timeout: stack_args['timeout_mins'] = timeout if stack is None: self.log.info("Performing Heat stack create") orchestration_client.stacks.create(**stack_args) else: self.log.info("Performing Heat stack update") # Make sure existing parameters for stack are reused stack_args['existing'] = 'true' orchestration_client.stacks.update(stack.id, **stack_args) create_result = utils.wait_for_stack_ready( orchestration_client, stack_name) if not create_result: if stack is None: raise Exception("Heat Stack create failed.") else: raise Exception("Heat Stack update failed.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pre_heat_deploy(self): """Setup before the Heat stack create or update has been done."""
clients = self.app.client_manager compute_client = clients.compute self.log.debug("Checking hypervisor stats") if utils.check_hypervisor_stats(compute_client) is None: raise exceptions.DeploymentError( "Expected hypervisor stats not met") 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 _deploy_tripleo_heat_templates(self, stack, parsed_args): """Deploy the fixed templates in TripleO Heat Templates"""
clients = self.app.client_manager network_client = clients.network parameters = self._update_paramaters( parsed_args, network_client, stack) utils.check_nodes_count( self.app.client_manager.rdomanager_oscplugin.baremetal(), stack, parameters, { 'ControllerCount': 1, 'ComputeCount': 1, 'ObjectStorageCount': 0, 'BlockStorageCount': 0, 'CephStorageCount': 0, } ) tht_root = parsed_args.templates print("Deploying templates in the directory {0}".format( os.path.abspath(tht_root))) self.log.debug("Creating Environment file") env_path = utils.create_environment_file() if stack is None: self.log.debug("Creating Keystone certificates") keystone_pki.generate_certs_into_json(env_path, False) resource_registry_path = os.path.join(tht_root, RESOURCE_REGISTRY_NAME) environments = [resource_registry_path, env_path] if parsed_args.rhel_reg: reg_env = self._create_registration_env(parsed_args) environments.extend(reg_env) if parsed_args.environment_files: environments.extend(parsed_args.environment_files) overcloud_yaml = os.path.join(tht_root, OVERCLOUD_YAML_NAME) self._heat_deploy(stack, parsed_args.stack, overcloud_yaml, parameters, environments, parsed_args.timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def well_fields(self, well_x=1, well_y=1): """All ScanFieldData elements of given well. Parameters well_x : int well_y : int Returns ------- list of lxml.objectify.ObjectifiedElement All ScanFieldData elements of given well. """
xpath = './ScanFieldArray/ScanFieldData' xpath += _xpath_attrib('WellX', well_x) xpath += _xpath_attrib('WellY', well_y) return self.root.findall(xpath)