{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nconverting a value to a datetime object.", "response": "def convert_datetime(value, parameter):\n '''\n Converts to datetime.datetime:\n '', '-', None convert to parameter default\n The first matching format in settings.DATETIME_INPUT_FORMATS converts to datetime\n '''\n value = _check_default(value, parameter, ( '', '-', None ))\n if value is None or isinstance(value, datetime.datetime):\n return value\n for fmt in settings.DATETIME_INPUT_FORMATS:\n try:\n return datetime.datetime.strptime(value, fmt)\n except (ValueError, TypeError):\n continue\n raise ValueError(\"`{}` does not match a format in settings.DATETIME_INPUT_FORMATS\".format(value))"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef convert_date(value, parameter):\n '''\n Converts to datetime.date:\n '', '-', None convert to parameter default\n The first matching format in settings.DATE_INPUT_FORMATS converts to datetime\n '''\n value = _check_default(value, parameter, ( '', '-', None ))\n if value is None or isinstance(value, datetime.date):\n return value\n for fmt in settings.DATE_INPUT_FORMATS:\n try:\n return datetime.datetime.strptime(value, fmt).date()\n except (ValueError, TypeError):\n continue\n raise ValueError(\"`{}` does not match a format in settings.DATE_INPUT_FORMATS\".format(value))", "response": "Converts a value to a datetime. date object."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef convert_id_to_model(value, parameter):\n '''\n Converts to a Model object.\n '', '-', '0', None convert to parameter default\n Anything else is assumed an object id and sent to `.get(id=value)`.\n '''\n value = _check_default(value, parameter, ( '', '-', '0', None ))\n if isinstance(value, (int, str)): # only convert if we have the id\n try:\n return parameter.type.objects.get(id=value)\n except (MultipleObjectsReturned, ObjectDoesNotExist) as e:\n raise ValueError(str(e))\n return value", "response": "Converts an id to a Model object."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _check_default(value, parameter, default_chars):\n '''Returns the default if the value is \"empty\"'''\n # not using a set here because it fails when value is unhashable\n if value in default_chars:\n if parameter.default is inspect.Parameter.empty:\n raise ValueError('Value was empty, but no default value is given in view function for parameter: {} ({})'.format(parameter.position, parameter.name))\n return parameter.default\n return value", "response": "Checks if the value is empty and returns the default if it is empty"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef protocol(handler, cfg):\n # Stages\n if 'stages' not in cfg:\n raise ValueError('Protocol must include stages of simulation')\n\n pos, vel, box = handler.positions, handler.velocities, handler.box\n stages = cfg.pop('stages')\n for stage_options in stages:\n options = DEFAULT_OPTIONS.copy()\n options.update(cfg)\n stage_system_options = prepare_system_options(stage_options)\n options.update(stage_options)\n options['system_options'].update(stage_system_options)\n stage = Stage(handler, positions=pos, velocities=vel, box=box,\n total_stages=len(stages), **options)\n pos, vel, box = stage.run()\n del stage", "response": "Run all the stages in protocol\n "}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef run(self):\n if self.verbose:\n status = '#{}'.format(self.stage_index)\n if self.total_stages is not None:\n status += '/{}'.format(self.total_stages)\n status += ': {}'.format(self.name)\n pieces = []\n if self.restrained_atoms is not None:\n pieces.append('restrained {}'.format(self.restrained_atoms))\n if self.constrained_atoms is not None:\n pieces.append('constrained {}'.format(self.constrained_atoms))\n if self.distance_restrained_atoms is not None:\n pieces.append('distance restrained for {} atom pairs'.format(len(self.distance_restrained_atoms)))\n if pieces:\n status += ' [{}]'.format(', '.join(pieces))\n logger.info(status)\n\n # Add forces\n self.apply_restraints()\n self.apply_constraints()\n\n if self.barostat:\n self.apply_barostat()\n\n if self.minimization:\n if self.verbose:\n logger.info(' Minimizing...')\n self.minimize()\n\n uses_pbc = self.system.usesPeriodicBoundaryConditions()\n if self.steps:\n # Stdout progress\n if self.report and self.progress_reporter not in self.simulation.reporters:\n self.simulation.reporters.append(self.progress_reporter)\n\n # Log report\n if self.report and self.log_reporter not in self.simulation.reporters:\n self.simulation.reporters.append(self.log_reporter)\n\n # Trajectory / movie files\n if self.trajectory and self.trajectory_reporter not in self.simulation.reporters:\n self.simulation.reporters.append(self.trajectory_reporter)\n\n # Checkpoint or restart files\n if self.restart and self.restart_reporter not in self.simulation.reporters:\n self.simulation.reporters.append(self.restart_reporter)\n\n # MD simulation\n if self.verbose:\n pbc = 'PBC ' if uses_pbc else ''\n conditions = 'NPT' if self.barostat else 'NVT'\n logger.info(' Running {}MD for {} steps @ {}K, {}'.format(pbc, self.steps,\n self.temperature,\n conditions))\n\n with self.handle_exceptions():\n self.simulate()\n\n if self.save_state_at_end:\n path = self.new_filename(suffix='.state')\n self.simulation.saveState(path)\n\n # Save and return state\n state = self.simulation.context.getState(getPositions=True, getVelocities=True,\n enforcePeriodicBox=uses_pbc)\n\n return state.getPositions(), state.getVelocities(), state.getPeriodicBoxVectors()", "response": "Runs the MD simulation."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nminimize energy of the system until meeting tolerance or max_iterations.", "response": "def minimize(self, tolerance=None, max_iterations=None):\n \"\"\"\n Minimize energy of the system until meeting `tolerance` or\n performing `max_iterations`.\n \"\"\"\n if tolerance is None:\n tolerance = self.minimization_tolerance\n if max_iterations is None:\n max_iterations = self.minimization_max_iterations\n self.simulation.minimizeEnergy(tolerance * u.kilojoules_per_mole, max_iterations)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nadvance simulation n steps", "response": "def simulate(self, steps=None):\n \"\"\"\n Advance simulation n steps\n \"\"\"\n if steps is None:\n steps = self.steps\n self.simulation.step(steps)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning a custom force that restrains atoms to fix their positions while allowing severe clashes and so on.", "response": "def restraint_force(self, indices=None, strength=5.0):\n \"\"\"\n Force that restrains atoms to fix their positions, while allowing\n tiny movement to resolve severe clashes and so on.\n\n Returns\n -------\n force : simtk.openmm.CustomExternalForce\n A custom force to restrain the selected atoms\n \"\"\"\n if self.system.usesPeriodicBoundaryConditions():\n expression = 'k*periodicdistance(x, y, z, x0, y0, z0)^2'\n else:\n expression = 'k*((x-x0)^2 + (y-y0)^2 + (z-z0)^2)'\n force = mm.CustomExternalForce(expression)\n force.addGlobalParameter('k', strength*u.kilocalories_per_mole/u.angstroms**2)\n force.addPerParticleParameter('x0')\n force.addPerParticleParameter('y0')\n force.addPerParticleParameter('z0')\n positions = self.positions if self.positions is not None else self.handler.positions\n if indices is None:\n indices = range(self.handler.topology.getNumAtoms())\n for i, index in enumerate(indices):\n force.addParticle(i, positions[index].value_in_unit(u.nanometers))\n return force"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn a force for a set of atoms and distances.", "response": "def distance_restraint_force(self, atoms, distances, strengths):\n \"\"\"\n Parameters\n ----------\n atoms : tuple of tuple of int or str\n Pair of atom indices to be restrained, with shape (n, 2),\n like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL.\n distances : tuple of float\n Equilibrium distances for each pair\n strengths : tuple of float\n Force constant for each pair\n \"\"\"\n system = self.system\n force = mm.HarmonicBondForce()\n force.setUsesPeriodicBoundaryConditions(self.system.usesPeriodicBoundaryConditions())\n for pair, distance, strength in zip(atoms, distances, strengths):\n indices = []\n for atom in pair:\n if isinstance(atom, str):\n index = self.subset(atom)\n if len(index) != 1:\n raise ValueError('Distance restraint for selection `{}` returns != 1 atom!: {}'\n .format(atom, index))\n indices.append(int(index[0]))\n elif isinstance(atom, (int, float)):\n indices.append(int(atom))\n else:\n raise ValueError('Distance restraint atoms must be int or str DSL selections')\n if distance == 'current':\n pos = self.positions or system.positions\n distance = np.linalg.norm(pos[indices[0]] - pos[indices[1]])\n\n force.addBond(indices[0], indices[1], distance*u.nanometers,\n strength*u.kilocalories_per_mole/u.angstroms**2)\n return force"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef subset(self, selector):\n if isinstance(selector, (list, tuple)):\n return map(int, selector)\n selector = SELECTORS.get(selector, selector)\n mdtop = MDTrajTopology.from_openmm(self.handler.topology)\n return mdtop.select(selector)", "response": "Returns a list of atom indices corresponding to a MDTraj DSL\n query."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef handle_exceptions(self, verbose=True):\n try:\n yield\n except (KeyboardInterrupt, Exception) as ex:\n if not self.attempt_rescue:\n raise ex\n if isinstance(ex, KeyboardInterrupt):\n reraise = False\n answer = timed_input('\\n\\nDo you want to save current state? (y/N): ')\n if answer and answer.lower() not in ('y', 'yes'):\n if verbose:\n sys.exit('Ok, bye!')\n else:\n reraise = True\n logger.error('\\n\\nAn error occurred: %s', ex)\n if verbose:\n logger.info('Saving state...')\n try:\n self.backup_simulation()\n except Exception:\n if verbose:\n logger.error('FAILED :(')\n else:\n if verbose:\n logger.info('SUCCESS!')\n finally:\n if reraise:\n raise ex\n sys.exit()", "response": "Handle exceptions and attempt to save the current state of the simulation."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef backup_simulation(self):\n path = self.new_filename(suffix='_emergency.state')\n self.simulation.saveState(path)\n uses_pbc = self.system.usesPeriodicBoundaryConditions()\n state_kw = dict(getPositions=True, getVelocities=True,\n getForces=True, enforcePeriodicBox=uses_pbc,\n getParameters=True, getEnergy=True)\n state = self.simulation.context.getState(**state_kw)\n for reporter in self.simulation.reporters:\n if not isinstance(reporter, app.StateDataReporter):\n reporter.report(self.simulation, state)", "response": "Creates an emergency report run and saves the state of the simulation context to disk."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngetting parse and prepare input file.", "response": "def prepare_input(argv=None):\n \"\"\"\n Get, parse and prepare input file.\n \"\"\"\n p = ArgumentParser(description='InsiliChem Ommprotocol: '\n 'easy to deploy MD protocols for OpenMM')\n p.add_argument('input', metavar='INPUT FILE', type=extant_file,\n help='YAML input file')\n p.add_argument('--version', action='version', version='%(prog)s v{}'.format(__version__))\n p.add_argument('-c', '--check', action='store_true',\n help='Validate input file only')\n args = p.parse_args(argv if argv else sys.argv[1:])\n\n jinja_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True)\n # Load config file\n with open(args.input) as f:\n rendered = jinja_env.from_string(f.read()).render()\n cfg = yaml.load(rendered, Loader=YamlLoader)\n # Paths and dirs\n from .md import SYSTEM_OPTIONS\n cfg['_path'] = os.path.abspath(args.input)\n cfg['system_options'] = prepare_system_options(cfg, defaults=SYSTEM_OPTIONS)\n cfg['outputpath'] = sanitize_path_for_file(cfg.get('outputpath', '.'), args.input)\n\n if not args.check:\n with ignored_exceptions(OSError):\n os.makedirs(cfg['outputpath'])\n\n handler = prepare_handler(cfg)\n\n return handler, cfg, args"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nloading all files into single object.", "response": "def prepare_handler(cfg):\n \"\"\"\n Load all files into single object.\n \"\"\"\n positions, velocities, box = None, None, None\n _path = cfg.get('_path', './')\n forcefield = cfg.pop('forcefield', None)\n topology_args = sanitize_args_for_file(cfg.pop('topology'), _path)\n\n if 'checkpoint' in cfg:\n restart_args = sanitize_args_for_file(cfg.pop('checkpoint'), _path)\n restart = Restart.load(*restart_args)\n positions = restart.positions\n velocities = restart.velocities\n box = restart.box\n\n if 'positions' in cfg:\n positions_args = sanitize_args_for_file(cfg.pop('positions'), _path)\n positions = Positions.load(*positions_args)\n box = BoxVectors.load(*positions_args)\n\n if 'velocities' in cfg:\n velocities_args = sanitize_args_for_file(cfg.pop('velocities'), _path)\n velocities = Velocities.load(*velocities_args)\n\n if 'box' in cfg:\n box_args = sanitize_args_for_file(cfg.pop('box'), _path)\n box = BoxVectors.load(*box_args)\n\n options = {}\n for key in 'positions velocities box forcefield'.split():\n value = locals()[key]\n if value is not None:\n options[key] = value\n\n return SystemHandler.load(*topology_args, **options)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef prepare_system_options(cfg, defaults=None):\n d = {} if defaults is None else defaults.copy()\n if 'nonbondedMethod' in cfg:\n d['nonbondedMethod'] = warned_getattr(openmm_app, cfg.pop('nonbondedMethod'), None)\n if 'nonbondedCutoff' in cfg:\n d['nonbondedCutoff'] = cfg.pop('nonbondedCutoff') * u.nanometers\n if 'constraints' in cfg:\n d['constraints'] = warned_getattr(openmm_app, cfg.pop('constraints'), None)\n for key in ['rigidWater', 'ewaldErrorTolerance']:\n if key in cfg:\n d[key] = cfg.pop(key)\n if 'extra_system_options' in cfg:\n if 'implicitSolvent' in cfg['extra_system_options']:\n implicit_solvent = warned_getattr(\n openmm_app, cfg['extra_system_options']['implicitSolvent'], None)\n cfg['extra_system_options']['implicitSolvent'] = implicit_solvent\n d.update(cfg.pop('extra_system_options'))\n return d", "response": "Retrieve and delete system options from input configuration."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef process_forcefield(*forcefields):\n for forcefield in forcefields:\n if forcefield.endswith('.frcmod'):\n gaffmol2 = os.path.splitext(forcefield)[0] + '.gaff.mol2'\n yield create_ffxml_file([gaffmol2], [forcefield])\n else:\n yield forcefield", "response": "Yields a list of filenames if they are frcmods."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef statexml2pdb(topology, state, output=None):\n state = Restart.from_xml(state)\n system = SystemHandler.load(topology, positions=state.positions)\n if output is None:\n output = topology + '.pdb'\n system.write_pdb(output)", "response": "Given an OpenMM xml file containing the state of the simulation generate a PDB snapshot for easy visualization."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nextract a single frame structure from a trajectory.", "response": "def export_frame_coordinates(topology, trajectory, nframe, output=None):\n \"\"\"\n Extract a single frame structure from a trajectory.\n \"\"\"\n if output is None:\n basename, ext = os.path.splitext(trajectory)\n output = '{}.frame{}.inpcrd'.format(basename, nframe)\n\n # ParmEd sometimes struggles with certain PRMTOP files\n if os.path.splitext(topology)[1] in ('.top', '.prmtop'):\n top = AmberPrmtopFile(topology)\n mdtop = mdtraj.Topology.from_openmm(top.topology)\n traj = mdtraj.load_frame(trajectory, int(nframe), top=mdtop)\n structure = parmed.openmm.load_topology(top.topology, system=top.createSystem())\n structure.box_vectors = top.topology.getPeriodicBoxVectors()\n\n else: # standard protocol (the topology is loaded twice, though)\n traj = mdtraj.load_frame(trajectory, int(nframe), top=topology)\n structure = parmed.load_file(topology)\n\n structure.positions = traj.openmm_positions(0)\n\n if traj.unitcell_vectors is not None: # if frame provides box vectors, use those\n structure.box_vectors = traj.openmm_boxes(0)\n\n structure.save(output, overwrite=True)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef construct_include(self, node):\n\n filename = os.path.join(self._root, self.construct_scalar(node))\n filename = os.path.abspath(filename)\n extension = os.path.splitext(filename)[1].lstrip('.')\n\n with open(filename, 'r') as f:\n if extension in ('yaml', 'yml'):\n return yaml.load(f, Loader=self)\n else:\n return ''.join(f.readlines())", "response": "Construct include file referenced at node."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef from_pdb(cls, path, forcefield=None, loader=PDBFile, strict=True, **kwargs):\n pdb = loader(path)\n box = kwargs.pop('box', pdb.topology.getPeriodicBoxVectors())\n positions = kwargs.pop('positions', pdb.positions)\n velocities = kwargs.pop('velocities', getattr(pdb, 'velocities', None))\n\n if strict and not forcefield:\n from .md import FORCEFIELDS as forcefield\n logger.info('! Forcefields for PDB not specified. Using default: %s',\n ', '.join(forcefield))\n pdb.forcefield = ForceField(*list(process_forcefield(*forcefield)))\n\n return cls(master=pdb.forcefield, topology=pdb.topology, positions=positions,\n velocities=velocities, box=box, path=path, **kwargs)", "response": "Loads a SystemHandler from a PDB file."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nload a SystemHandler from an Amber. prmtop file.", "response": "def from_amber(cls, path, positions=None, strict=True, **kwargs):\n \"\"\"\n Loads Amber Parm7 parameters and topology file\n\n Parameters\n ----------\n path : str\n Path to *.prmtop or *.top file\n positions : simtk.unit.Quantity\n Atomic positions\n\n Returns\n -------\n prmtop : SystemHandler\n SystemHandler with topology\n \"\"\"\n if strict and positions is None:\n raise ValueError('Amber TOP/PRMTOP files require initial positions.')\n prmtop = AmberPrmtopFile(path)\n box = kwargs.pop('box', prmtop.topology.getPeriodicBoxVectors())\n return cls(master=prmtop, topology=prmtop.topology, positions=positions, box=box,\n path=path, **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef from_charmm(cls, path, positions=None, forcefield=None, strict=True, **kwargs):\n psf = CharmmPsfFile(path)\n if strict and forcefield is None:\n raise ValueError('PSF files require key `forcefield`.')\n if strict and positions is None:\n raise ValueError('PSF files require key `positions`.')\n psf.parmset = CharmmParameterSet(*forcefield)\n psf.loadParameters(psf.parmset)\n return cls(master=psf, topology=psf.topology, positions=positions, path=path,\n **kwargs)", "response": "Loads a SystemHandler from a Charmm structure file."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nloads a topology from a Desmond DMS file located at path.", "response": "def from_desmond(cls, path, **kwargs):\n \"\"\"\n Loads a topology from a Desmond DMS file located at `path`.\n\n Arguments\n ---------\n path : str\n Path to a Desmond DMS file\n \"\"\"\n dms = DesmondDMSFile(path)\n pos = kwargs.pop('positions', dms.getPositions())\n return cls(master=dms, topology=dms.getTopology(), positions=pos, path=path,\n **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef from_gromacs(cls, path, positions=None, forcefield=None, strict=True, **kwargs):\n if strict and positions is None:\n raise ValueError('Gromacs TOP files require initial positions.')\n box = kwargs.pop('box', None)\n top = GromacsTopFile(path, includeDir=forcefield, periodicBoxVectors=box)\n return cls(master=top, topology=top.topology, positions=positions, box=box,\n path=path, **kwargs)", "response": "Loads a topology from a Gromacs TOP file located at path."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef from_parmed(cls, path, *args, **kwargs):\n st = parmed.load_file(path, structure=True, *args, **kwargs)\n box = kwargs.pop('box', getattr(st, 'box', None))\n velocities = kwargs.pop('velocities', getattr(st, 'velocities', None))\n positions = kwargs.pop('positions', getattr(st, 'positions', None))\n return cls(master=st, topology=st.topology, positions=positions, box=box,\n velocities=velocities, path=path, **kwargs)", "response": "Load a new object from a ParmEd file."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nloading pickled topology. Careful with Python versions though!", "response": "def _pickle_load(path):\n \"\"\"\n Loads pickled topology. Careful with Python versions though!\n \"\"\"\n _, ext = os.path.splitext(path)\n topology = None\n if sys.version_info.major == 2:\n if ext == '.pickle2':\n with open(path, 'rb') as f:\n topology = pickle.load(f)\n elif ext in ('.pickle3', '.pickle'):\n with open(path, 'rb') as f:\n topology = pickle.load(f, protocol=3)\n elif sys.version_info.major == 3:\n if ext == '.pickle2':\n with open(path, 'rb') as f:\n topology = pickle.load(f)\n elif ext in ('.pickle3', '.pickle'):\n with open(path, 'rb') as f:\n topology = pickle.load(f)\n if topology is None:\n raise ValueError('File {} is not compatible with this version'.format(path))\n return topology"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ncreate an OpenMM system for every supported topology file with given system options.", "response": "def create_system(self, **system_options):\n \"\"\"\n Create an OpenMM system for every supported topology file with given system options\n \"\"\"\n if self.master is None:\n raise ValueError('Handler {} is not able to create systems.'.format(self))\n\n if isinstance(self.master, ForceField):\n system = self.master.createSystem(self.topology, **system_options)\n elif isinstance(self.master, (AmberPrmtopFile, GromacsTopFile, DesmondDMSFile)):\n system = self.master.createSystem(**system_options)\n elif isinstance(self.master, CharmmPsfFile):\n if not hasattr(self.master, 'parmset'):\n raise ValueError('PSF topology files require Charmm parameters.')\n system = self.master.createSystem(self.master.parmset, **system_options)\n else:\n raise NotImplementedError('Handler {} is not able to create systems.'.format(self))\n\n if self.has_box:\n system.setDefaultPeriodicBoxVectors(*self.box)\n return system"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\noutputting a PDB file with the current contents of the system.", "response": "def write_pdb(self, path):\n \"\"\"\n Outputs a PDB file with the current contents of the system\n \"\"\"\n if self.master is None and self.positions is None:\n raise ValueError('Topology and positions are needed to write output files.')\n with open(path, 'w') as f:\n PDBFile.writeFile(self.topology, self.positions, f)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef from_xsc(cls, path):\n\n def parse(path):\n \"\"\"\n Open and parses an XSC file into its fields\n\n Parameters\n ----------\n path : str\n Path to XSC file\n\n Returns\n -------\n namedxsc : namedtuple\n A namedtuple with XSC fields as names\n \"\"\"\n with open(path) as f:\n lines = f.readlines()\n NamedXsc = namedtuple('NamedXsc', lines[1].split()[1:])\n return NamedXsc(*map(float, lines[2].split()))\n\n xsc = parse(path)\n return u.Quantity([[xsc.a_x, xsc.a_y, xsc.a_z],\n [xsc.b_x, xsc.b_y, xsc.b_z],\n [xsc.c_x, xsc.c_y, xsc.c_z]], unit=u.angstroms)", "response": "Returns u. Quantity with box vectors from XSC file"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef from_csv(cls, path):\n with open(path) as f:\n fields = map(float, next(f).split(','))\n if len(fields) == 3:\n return u.Quantity([[fields[0], 0, 0],\n [0, fields[1], 0],\n [0, 0, fields[2]]], unit=u.nanometers)\n elif len(fields) == 9:\n return u.Quantity([fields[0:3],\n fields[3:6],\n fields[6:9]], unit=u.nanometers)\n else:\n raise ValueError('This type of CSV is not supported. Please '\n 'provide a comma-separated list of three or nine '\n 'floats in a single-line file.')", "response": "Returns a new instance of the class u. Quantity object from a CSV file."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef describeNextReport(self, simulation):\n steps = self.interval - simulation.currentStep % self.interval\n return steps, False, False, False, False", "response": "Get information about the next report for this object."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef report(self, simulation, state):\n if not self._initialized:\n self._initial_clock_time = datetime.now()\n self._initial_simulation_time = state.getTime()\n self._initial_steps = simulation.currentStep\n self._initialized = True\n\n steps = simulation.currentStep\n time = datetime.now() - self._initial_clock_time\n days = time.total_seconds()/86400.0\n ns = (state.getTime()-self._initial_simulation_time).value_in_unit(u.nanosecond)\n\n margin = ' ' * self.margin\n ns_day = ns/days\n delta = ((self.total_steps-steps)*time.total_seconds())/steps\n # remove microseconds to have cleaner output\n remaining = timedelta(seconds=int(delta))\n percentage = 100.0*steps/self.total_steps\n if ns_day:\n template = '{}{}/{} steps ({:.1f}%) - {} left @ {:.1f} ns/day \\r'\n else:\n template = '{}{}/{} steps ({:.1f}%) \\r'\n report = template.format(margin, steps, self.total_steps, percentage, remaining, ns_day)\n self._out.write(report)\n if hasattr(self._out, 'flush'):\n self._out.flush()", "response": "Generate a report.\n\n Parameters\n ----------\n simulation : Simulation\n The Simulation to generate a report for\n state : State\n The current state of the simulation"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef report(self, simulation, state):\n if not self._initialized:\n self._initialized = True\n\n self._steps[0] += self.interval\n positions = state.getPositions()\n\n # Serialize\n self._out.write(b''.join([b'\\nSTARTOFCHUNK\\n',\n pickle.dumps([self._steps[0], positions._value]),\n b'\\nENDOFCHUNK\\n']))\n if hasattr(self._out, 'flush'):\n self._out.flush()", "response": "Generate a report.\n\n Parameters\n ----------\n simulation : Simulation\n The Simulation to generate a report for\n state : State\n The current state of the simulation"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef assert_not_exists(path, sep='.'):\n name, ext = os.path.splitext(path)\n i = 1\n while os.path.exists(path):\n path = '{}{}{}{}'.format(name, sep, i, ext)\n i += 1\n return path", "response": "Checks if a file does not exist."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nmake sure object obj is of type types. Else raise TypeError.", "response": "def assertinstance(obj, types):\n \"\"\"\n Make sure object `obj` is of type `types`. Else, raise TypeError.\n \"\"\"\n if isinstance(obj, types):\n return obj\n raise TypeError('{} must be instance of {}'.format(obj, types))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef extant_file(path):\n if not os.path.exists(path):\n raise argparse.ArgumentTypeError(\"{} does not exist\".format(path))\n return path", "response": "Check if file exists with argparse. ArgumentParser"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nsort files taking into account potentially absent suffixes like 2000. 1000. 2000.", "response": "def sort_key_for_numeric_suffixes(path, sep='.', suffix_index=-2):\n \"\"\"\n Sort files taking into account potentially absent suffixes like\n somefile.dcd\n somefile.1000.dcd\n somefile.2000.dcd\n\n To be used with sorted(..., key=callable).\n \"\"\"\n chunks = path.split(sep)\n # Remove suffix from path and convert to int\n if chunks[suffix_index].isdigit():\n return sep.join(chunks[:suffix_index] + chunks[suffix_index+1:]), int(chunks[suffix_index])\n return path, 0"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef json_response(f, *args, **kwargs):\n try:\n result = f(*args, **kwargs)\n if isinstance(result, AJAXError):\n raise result\n except AJAXError as e:\n result = e.get_response()\n\n request = args[0]\n logger.warn('AJAXError: %d %s - %s', e.code, request.path, e.msg,\n exc_info=True,\n extra={\n 'status_code': e.code,\n 'request': request\n }\n )\n except Http404 as e:\n result = AJAXError(404, e.__str__()).get_response()\n except Exception as e:\n import sys\n exc_info = sys.exc_info()\n type, message, trace = exc_info\n if settings.DEBUG:\n import traceback\n tb = [{'file': l[0], 'line': l[1], 'in': l[2], 'code': l[3]} for\n l in traceback.extract_tb(trace)]\n result = AJAXError(500, message, traceback=tb).get_response()\n else:\n result = AJAXError(500, \"Internal server error.\").get_response()\n\n request = args[0]\n logger.error('Internal Server Error: %s' % request.path,\n exc_info=exc_info,\n extra={\n 'status_code': 500,\n 'request': request\n }\n )\n\n result['Content-Type'] = 'application/json'\n return result", "response": "A decorator that wraps a view in JSON."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef import_by_path(dotted_path, error_prefix=''):\n try:\n module_path, class_name = dotted_path.rsplit('.', 1)\n except ValueError:\n raise ImproperlyConfigured(\"%s%s doesn't look like a module path\" % (\n error_prefix, dotted_path))\n try:\n module = import_module(module_path)\n except ImportError as e:\n raise ImproperlyConfigured('%sError importing module %s: \"%s\"' % (\n error_prefix, module_path, e))\n try:\n attr = getattr(module, class_name)\n except AttributeError:\n raise ImproperlyConfigured(\n '%sModule \"%s\" does not define a \"%s\" attribute/class' % (\n error_prefix, module_path, class_name\n )\n )\n return attr", "response": "Imports a dotted module path and returns the attribute or class designated by the last name in the path. Raise ImproperlyConfigured if something goes wrong."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nloading an AJAX endpoint. This will load either an ad-hoc endpoint or it will load up a model endpoint depending on what it finds. It first attempts to load ``model`` as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if there is a ``ModelEndpoint`` for the given ``model``.", "response": "def endpoint_loader(request, application, model, **kwargs):\n \"\"\"Load an AJAX endpoint.\n\n This will load either an ad-hoc endpoint or it will load up a model\n endpoint depending on what it finds. It first attempts to load ``model``\n as if it were an ad-hoc endpoint. Alternatively, it will attempt to see if\n there is a ``ModelEndpoint`` for the given ``model``.\n \"\"\"\n if request.method != \"POST\":\n raise AJAXError(400, _('Invalid HTTP method used.'))\n\n try:\n module = import_module('%s.endpoints' % application)\n except ImportError as e:\n if settings.DEBUG:\n raise e\n else:\n raise AJAXError(404, _('AJAX endpoint does not exist.'))\n\n if hasattr(module, model):\n # This is an ad-hoc endpoint\n endpoint = getattr(module, model)\n else:\n # This is a model endpoint\n method = kwargs.get('method', 'create').lower()\n try:\n del kwargs['method']\n except:\n pass\n\n try:\n model_endpoint = ajax.endpoint.load(model, application, method,\n **kwargs)\n if not model_endpoint.authenticate(request, application, method):\n raise AJAXError(403, _('User is not authorized.'))\n\n endpoint = getattr(model_endpoint, method, False)\n\n if not endpoint:\n raise AJAXError(404, _('Invalid method.'))\n except NotRegistered:\n raise AJAXError(500, _('Invalid model.'))\n\n data = endpoint(request)\n if isinstance(data, HttpResponse):\n return data\n\n if isinstance(data, EnvelopedResponse):\n envelope = data.metadata\n payload = data.data\n else:\n envelope = {}\n payload = data\n\n envelope.update({\n 'success': True,\n 'data': payload,\n })\n\n return HttpResponse(json.dumps(envelope, cls=DjangoJSONEncoder,\n separators=(',', ':')))"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef list(self, request):\n\n max_items_per_page = getattr(self, 'max_per_page',\n getattr(settings, 'AJAX_MAX_PER_PAGE', 100))\n requested_items_per_page = request.POST.get(\"items_per_page\", 20)\n items_per_page = min(max_items_per_page, requested_items_per_page)\n current_page = request.POST.get(\"current_page\", 1)\n\n if not self.can_list(request.user):\n raise AJAXError(403, _(\"Access to this endpoint is forbidden\"))\n\n objects = self.get_queryset(request)\n\n paginator = Paginator(objects, items_per_page)\n\n try:\n page = paginator.page(current_page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n page = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), return empty list.\n page = EmptyPageResult()\n\n data = [encoder.encode(record) for record in page.object_list]\n return EnvelopedResponse(data=data, metadata={'total': paginator.count})", "response": "List objects of a model."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nextract the data from the POST request.", "response": "def _extract_data(self, request):\n \"\"\"Extract data from POST.\n\n Handles extracting a vanilla Python dict of values that are present\n in the given model. This also handles instances of ``ForeignKey`` and\n will convert those to the appropriate object instances from the\n database. In other words, it will see that user is a ``ForeignKey`` to\n Django's ``User`` class, assume the value is an appropriate pk, and\n load up that record.\n \"\"\"\n data = {}\n for field, val in six.iteritems(request.POST):\n if field in self.immutable_fields:\n continue # Ignore immutable fields silently.\n\n if field in self.fields:\n field_obj = self.model._meta.get_field(field)\n val = self._extract_value(val)\n if isinstance(field_obj, models.ForeignKey):\n if field_obj.null and not val:\n clean_value = None\n else:\n clean_value = field_obj.rel.to.objects.get(pk=val)\n else:\n clean_value = field_obj.to_python(val)\n data[smart_str(field)] = clean_value\n\n return data"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _get_record(self):\n if not self.pk:\n raise AJAXError(400, _('Invalid request for record.'))\n\n try:\n return self.model.objects.get(pk=self.pk)\n except self.model.DoesNotExist:\n raise AJAXError(404, _('%s with id of \"%s\" not found.') % (\n self.model.__name__, self.pk))", "response": "Fetch a given record from the database along with throwing an anonymization of AJAXError."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef authenticate(self, request, application, method):\n return self.authentication.is_authenticated(request, application, method)", "response": "Authenticate the AJAX request."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nget all entries of a space.", "response": "def all(self, query=None):\n \"\"\"\n Gets all entries of a space.\n \"\"\"\n\n if query is None:\n query = {}\n\n if self.content_type_id is not None:\n query['content_type'] = self.content_type_id\n\n normalize_select(query)\n\n return super(EntriesProxy, self).all(query=query)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nget a single entry by ID.", "response": "def find(self, entry_id, query=None):\n \"\"\"\n Gets a single entry by ID.\n \"\"\"\n\n if query is None:\n query = {}\n\n if self.content_type_id is not None:\n query['content_type'] = self.content_type_id\n\n normalize_select(query)\n\n return super(EntriesProxy, self).find(entry_id, query=query)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create(self, resource_id=None, attributes=None, **kwargs):\n\n if self.content_type_id is not None:\n if attributes is None:\n attributes = {}\n attributes['content_type_id'] = self.content_type_id\n\n return super(EntriesProxy, self).create(resource_id=resource_id, attributes=attributes)", "response": "Creates an entry with a given ID and attributes."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncreates a webhook with given attributes.", "response": "def create(self, attributes=None, **kwargs):\n \"\"\"\n Creates a webhook with given attributes.\n \"\"\"\n\n return super(WebhooksProxy, self).create(resource_id=None, attributes=attributes)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef camel_case(snake_str):\n\n components = snake_str.split('_')\n # We capitalize the first letter of each component except the first one\n # with the 'title' method and join them together.\n return components[0] + \"\".join(x.title() for x in components[1:])", "response": "Return a camel - cased version of a string."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef normalize_select(query):\n\n if 'select' not in query:\n return\n\n if isinstance(\n query['select'],\n str_type()):\n query['select'] = [s.strip() for s in query['select'].split(',')]\n\n query['select'] = [s for s\n in query['select']\n if not s.startswith('sys.')]\n\n if 'sys' not in query['select']:\n query['select'].append('sys')", "response": "Normalizes the select operator in the query."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the JSON representation of the environment.", "response": "def to_json(self):\n \"\"\"\n Returns the JSON representation of the environment.\n \"\"\"\n\n result = super(Environment, self).to_json()\n result.update({\n 'name': self.name\n })\n\n return result"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef content_types(self):\n\n return EnvironmentContentTypesProxy(self._client, self.space.id, self.id)", "response": "Provides access to content types of an environment."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef entries(self):\n\n return EnvironmentEntriesProxy(self._client, self.space.id, self.id)", "response": "Provides access to entry management methods."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nproviding access to asset management methods.", "response": "def assets(self):\n \"\"\"\n Provides access to asset management methods.\n\n API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/assets\n\n :return: :class:`EnvironmentAssetsProxy \u041b\u0430\u0431\u043e\u0440\u0430\u0442\u043e\u0440\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440 \n or\n {% load djutils %}\n ...\n {% sort_th 'order__lab_number' '\u041b\u0430\u0431\u043e\u0440\u0430\u0442\u043e\u0440\u043d\u044b\u0439 \u043d\u043e\u043c\u0435\u0440' %}\n\n\n \"\"\"\n current_param, current_reversed = sort_key_process(request, sort_key)\n\n except_params = except_params or []\n except_params.append(sort_key)\n\n base_url = url_params(request, except_params=except_params, as_is=True)\n\n sort_params = {}\n revers_sort = revers_sort or set()\n url_connector = '?' if request.get_full_path() == request.path else \"&\"\n for p in params:\n sort_params[p] = {}\n if current_param and p == current_param:\n prefix = '' if current_reversed else '-'\n sort_params[p]['url'] = base_url + \"%s%s=%s\" % (url_connector, sort_key, prefix + current_param)\n sort_params[p]['is_reversed'] = current_reversed\n sort_params[p]['is_current'] = True\n else:\n default_direction = '-' if p in revers_sort else ''\n sort_params[p]['url'] = base_url + \"%s%s=%s%s\" % (url_connector, sort_key, default_direction, p)\n sort_params[p]['is_reversed'] = False\n sort_params[p]['is_current'] = False\n\n return sort_params"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nprocessing sort key for sorting", "response": "def sort_key_process(request, sort_key='sort'):\n \"\"\"\n process sort-parameter value (for example, \"-name\")\n return:\n current_param - field for sorting (\"name)\n current_reversed - revers flag (True)\n \"\"\"\n current = request.GET.get(sort_key)\n current_reversed = False\n current_param = None\n if current:\n mo = re.match(r'^(-?)(\\w+)$', current) # exclude first \"-\" (if exist)\n if mo:\n current_reversed = mo.group(1) == '-'\n current_param = mo.group(2)\n\n return current_param, current_reversed"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef transform_form_error(form, verbose=True):\n errors = []\n for field, err_msg in form.errors.items():\n if field == '__all__': # general errors\n errors.append(', '.join(err_msg))\n else: # field errors\n field_name = field\n if verbose and field in form.fields:\n field_name = form.fields[field].label or field\n errors.append('%s: %s' % (field_name, ', '.join(err_msg)))\n return errors", "response": "transform form errors to list like\n articles"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef process_date_from_to_options(options, to_datetime=False, default_dt_to=False):\n start_time = datetime.datetime.now()\n\n if options.get('last_week'):\n dt_from = start_time - datetime.timedelta(days=7)\n dt_to = start_time\n\n elif options.get('last_day'):\n dt_from = start_time - datetime.timedelta(days=1)\n dt_to = start_time\n\n elif options.get('last_2hours'):\n dt_from = start_time - datetime.timedelta(hours=2)\n dt_to = start_time\n\n else:\n from_str = options.get('from')\n if from_str:\n try:\n dt_from = iso_to_datetime(from_str)\n except:\n dt_from = iso_to_date(from_str)\n else:\n dt_from = None\n\n to_str = options.get('to')\n if to_str:\n try:\n dt_to = iso_to_datetime(to_str)\n except:\n dt_to = iso_to_date(to_str)\n else:\n dt_to = None\n\n if default_dt_to and not dt_to:\n dt_to = datetime.datetime(2100, 1, 1)\n\n if to_datetime:\n if isinstance(dt_from, datetime.date):\n dt_from = date_to_datetime(dt_from)\n if isinstance(dt_to, datetime.date):\n dt_to = date_to_datetime_lte(dt_to)\n\n return dt_from, dt_to", "response": "Process date from options to options dt_to"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nyielding n items from iterable into n - sized lists.", "response": "def _chunked(iterable, n):\n \"\"\"\n Collect data into chunks of up to length n.\n :type iterable: Iterable[T]\n :type n: int\n :rtype: Iterator[list[T]]\n \"\"\"\n it = iter(iterable)\n while True:\n chunk = list(islice(it, n))\n if chunk:\n yield chunk\n else:\n return"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets gender information for a list of names.", "response": "def get(self, names, country_id=None, language_id=None, retheader=False):\n \"\"\"\n Look up gender for a list of names.\n Can optionally refine search with locale info.\n May make multiple requests if there are more names than\n can be retrieved in one call.\n\n :param names: List of names.\n :type names: Iterable[str]\n :param country_id: Optional ISO 3166-1 alpha-2 country code.\n :type country_id: Optional[str]\n :param language_id: Optional ISO 639-1 language code.\n :type language_id: Optional[str]\n :param retheader: Optional\n :type retheader: Optional[boolean]\n :return:\n If retheader is False:\n List of dicts containing 'name', 'gender',\n 'probability', 'count' keys. If 'gender' is None,\n 'probability' and 'count' will be omitted.\n else:\n A dict containing 'data' and 'headers' keys.\n Data is the same as when retheader is False.\n Headers are the response header\n (a requests.structures.CaseInsensitiveDict).\n If multiple requests were made,\n the header will be from the last one.\n :rtype: Union[dict, Sequence[dict]]\n :raises GenderizeException: if API server returns HTTP error code.\n \"\"\"\n responses = [\n self._get_chunk(name_chunk, country_id, language_id)\n for name_chunk\n in _chunked(names, Genderize.BATCH_SIZE)\n ]\n data = list(chain.from_iterable(\n response.data for response in responses\n ))\n if retheader:\n return {\n \"data\": data,\n \"headers\": responses[-1].headers,\n }\n else:\n return data"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nlooking up gender for a single name.", "response": "def get1(self, name, **kwargs):\n \"\"\"\n Look up gender for a single name.\n See :py:meth:`get`.\n Doesn't support retheader option.\n \"\"\"\n if 'retheader' in kwargs:\n raise GenderizeException(\n \"get1() doesn't support the retheader option.\")\n return self.get([name], **kwargs)[0]"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncreating a proxy for a variable.", "response": "def _make_proxy(self, varname, parent=None, constructor=MlabObjectProxy):\n \"\"\"Creates a proxy for a variable.\n\n XXX create and cache nested proxies also here.\n \"\"\"\n # FIXME why not just use gensym here?\n proxy_val_name = \"PROXY_VAL%d__\" % self._proxy_count\n self._proxy_count += 1\n mlabraw.eval(self._session, \"%s = %s;\" % (proxy_val_name, varname))\n res = constructor(self, proxy_val_name, parent)\n self._proxies[proxy_val_name] = res\n return res"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _get(self, name, remove=False):\n # FIXME should this really be needed in normal operation?\n if name in self._proxies: return self._proxies[name]\n varname = name\n vartype = self._var_type(varname)\n if vartype in self._mlabraw_can_convert:\n var = mlabraw.get(self._session, varname)\n if isinstance(var, ndarray):\n if self._flatten_row_vecs and numpy.shape(var)[0] == 1:\n var.shape = var.shape[1:2]\n elif self._flatten_col_vecs and numpy.shape(var)[1] == 1:\n var.shape = var.shape[0:1]\n if self._array_cast:\n var = self._array_cast(var)\n else:\n var = None\n if self._dont_proxy.get(vartype):\n # manual conversions may fail (e.g. for multidimensional\n # cell arrays), in that case just fall back on proxying.\n try:\n var = self._manually_convert(varname, vartype)\n except MlabConversionError: pass\n if var is None:\n # we can't convert this to a python object, so we just\n # create a proxy, and don't delete the real matlab\n # reference until the proxy is garbage collected\n var = self._make_proxy(varname)\n if remove:\n mlabraw.eval(self._session, \"clear('%s');\" % varname)\n return var", "response": "Directly access a variable in matlab space."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef open(self, visible=False):\n if self.client:\n raise MatlabConnectionError('Matlab(TM) COM client is still active. Use close to '\n 'close it')\n self.client = win32com.client.Dispatch('matlab.application')\n self.client.visible = visible", "response": "Open the current COM client."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef eval(self, expression, identify_erros=True):\n #print expression\n self._check_open()\n ret = self.client.Execute(expression)\n #print ret\n if identify_erros and ret.rfind('???') != -1:\n begin = ret.rfind('???') + 4\n raise MatlabError(ret[begin:])\n return ret", "response": "Evaluates a matlab expression synchronously."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get(self, names_to_get, convert_to_numpy=True):\n self._check_open()\n single_itme = isinstance(names_to_get, (unicode, str))\n if single_itme:\n names_to_get = [names_to_get]\n ret = {}\n for name in names_to_get:\n ret[name] = self.client.GetWorkspaceData(name, 'base')\n # TODO(daniv): Do we really want to reduce dimensions like that? what if this a row vector?\n while isinstance(ret[name], (tuple, list)) and len(ret[name]) == 1:\n ret[name] = ret[name][0]\n if convert_to_numpy and isinstance(ret[name], (tuple, list)):\n ret[name] = np.array(ret[name])\n if single_itme:\n return ret.values()[0]\n return ret", "response": "Loads the requested variables from the matlab com client."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef put(self, name_to_val):\n self._check_open()\n for name, val in name_to_val.iteritems():\n # First try to put data as a matrix:\n try:\n self.client.PutFullMatrix(name, 'base', val, None)\n except:\n self.client.PutWorkspaceData(name, 'base', val)", "response": "Loads a dictionary of variable names into the matlab com client."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nopens MATLAB using specified connection or DCOM + protocol on Windows where matlab_location is set.", "response": "def open():\n global _MATLAB_RELEASE\n '''Opens MATLAB using specified connection (or DCOM+ protocol on Windows)where matlab_location '''\n if is_win:\n ret = MatlabConnection()\n ret.open()\n return ret\n else:\n if settings.MATLAB_PATH != 'guess':\n matlab_path = settings.MATLAB_PATH + '/bin/matlab'\n elif _MATLAB_RELEASE != 'latest':\n matlab_path = discover_location(_MATLAB_RELEASE)\n else:\n # Latest release is found in __init__.by, i.e. higher logical level\n raise MatlabReleaseNotFound('Please select a matlab release or set its location.')\n try:\n ret = MatlabConnection(matlab_path)\n ret.open()\n except Exception:\n #traceback.print_exc(file=sys.stderr)\n raise MatlabReleaseNotFound('Could not open matlab, is it in %s?' % matlab_path)\n return ret"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _list_releases():\n '''\n Tries to guess matlab process release version and location path on\n osx machines.\n\n The paths we will search are in the format:\n /Applications/MATLAB_R[YEAR][VERSION].app/bin/matlab\n We will try the latest version first. If no path is found, None is reutrned.\n '''\n if is_linux():\n base_path = '/usr/local/MATLAB/R%d%s/bin/matlab'\n else:\n # assume mac\n base_path = '/Applications/MATLAB_R%d%s.app/bin/matlab'\n years = range(2050,1990,-1)\n release_letters = ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')\n for year in years:\n for letter in release_letters:\n release = 'R%d%s' % (year, letter)\n matlab_path = base_path % (year, letter)\n if os.path.exists(matlab_path):\n yield (release, matlab_path)", "response": "Yields a list of all available MATLAB process releases and location paths."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef is_valid_release_version(version):\n '''Checks that the given version code is valid.'''\n return version is not None and len(version) == 6 and version[0] == 'R' \\\n and int(version[1:5]) in range(1990, 2050) \\\n and version[5] in ('h', 'g', 'f', 'e', 'd', 'c', 'b', 'a')", "response": "Checks that the given version code is valid."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef find_matlab_version(process_path):\n bin_path = os.path.dirname(process_path)\n matlab_path = os.path.dirname(bin_path)\n matlab_dir_name = os.path.basename(matlab_path)\n version = matlab_dir_name\n if not is_linux():\n version = matlab_dir_name.replace('MATLAB_', '').replace('.app', '')\n if not is_valid_release_version(version):\n return None\n return version", "response": "Tries to guess matlab s version according to its process path."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef open(self, print_matlab_welcome=False):\n '''Opens the matlab process.'''\n if self.process and not self.process.returncode:\n raise MatlabConnectionError('Matlab(TM) process is still active. Use close to '\n 'close it')\n self.process = subprocess.Popen(\n [self.matlab_process_path, '-nojvm', '-nodesktop'],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL)\n fcntl.fcntl(self.process.stdout, fcntl.F_SETFL, flags| os.O_NONBLOCK)\n\n if print_matlab_welcome:\n self._sync_output()\n else:\n self._sync_output(None)", "response": "Opens the matlab process."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nevaluates a matlab expression synchronously.", "response": "def eval(self,\n expression,\n identify_errors=True,\n print_expression=True,\n on_new_output=sys.stdout.write):\n \"\"\" Evaluates a matlab expression synchronously.\n\n If identify_erros is true, and the last output line after evaluating the\n expressions begins with '???' and excpetion is thrown with the matlab error\n following the '???'.\n If on_new_output is not None, it will be called whenever a new output is\n encountered. The default value prints the new output to the screen.\n The return value of the function is the matlab output following the call.\n \"\"\"\n self._check_open()\n if print_expression:\n print expression\n self.process.stdin.write(expression)\n self.process.stdin.write('\\n')\n ret = self._sync_output(on_new_output)\n # TODO(dani): Use stderr to identify errors.\n if identify_errors and ret.rfind('???') != -1:\n begin = ret.rfind('???') + 4\n end = ret.find('\\n', begin)\n raise MatlabError(ret[begin:end])\n return ret"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef put(self, name_to_val, oned_as='row', on_new_output=None):\n self._check_open()\n # We can't give stdin to mlabio.savemat because it needs random access :(\n temp = StringIO()\n mlabio.savemat(temp, name_to_val, oned_as=oned_as)\n temp.seek(0)\n temp_str = temp.read()\n temp.close()\n self.process.stdin.write('load stdio;\\n')\n self._read_until('ack load stdio\\n', on_new_output=on_new_output)\n self.process.stdin.write(temp_str)\n #print 'sent %d kb' % (len(temp_str) / 1024)\n self._read_until('ack load finished\\n', on_new_output=on_new_output)\n self._sync_output(on_new_output=on_new_output)", "response": "Loads a dictionary of variable names into the matlab shell."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get(self,\n names_to_get,\n extract_numpy_scalars=True,\n on_new_output=None):\n \"\"\" Loads the requested variables from the matlab shell.\n\n names_to_get can be either a variable name, a list of variable names, or\n None.\n If it is a variable name, the values is returned.\n If it is a list, a dictionary of variable_name -> value is returned.\n If it is None, a dictionary with all variables is returned.\n\n If extract_numpy_scalars is true, the method will convert numpy scalars\n (0-dimension arrays) to a regular python variable.\n \"\"\"\n self._check_open()\n single_item = isinstance(names_to_get, (unicode, str))\n if single_item:\n names_to_get = [names_to_get]\n if names_to_get == None:\n self.process.stdin.write('save stdio;\\n')\n else:\n # Make sure that we throw an excpetion if the names are not defined.\n for name in names_to_get:\n self.eval('%s;' % name, print_expression=False, on_new_output=on_new_output)\n #print 'save(\\'stdio\\', \\'%s\\');\\n' % '\\', \\''.join(names_to_get)\n self.process.stdin.write(\n \"save('stdio', '%s', '-v7');\\n\" % '\\', \\''.join(names_to_get))\n # We have to read to a temp buffer because mlabio.loadmat needs\n # random access :(\n self._read_until('start_binary\\n', on_new_output=on_new_output)\n #print 'got start_binary'\n temp_str = self._sync_output(on_new_output=on_new_output)\n #print 'got all outout'\n # Remove expected output and \"\\n>>\"\n # TODO(dani): Get rid of the unecessary copy.\n # MATLAB 2010a adds an extra >> so we need to remove more spaces.\n if self.matlab_version == (2010, 'a'):\n temp_str = temp_str[:-len(self.expected_output_end)-6]\n else:\n temp_str = temp_str[:-len(self.expected_output_end)-3]\n temp = StringIO(temp_str)\n #print ('____')\n #print len(temp_str)\n #print ('____')\n ret = mlabio.loadmat(temp, chars_as_strings=True, squeeze_me=True)\n #print '******'\n #print ret\n #print '******'\n temp.close()\n if single_item:\n return ret.values()[0]\n for key in ret.iterkeys():\n while ret[key].shape and ret[key].shape[-1] == 1:\n ret[key] = ret[key][0]\n if extract_numpy_scalars:\n if isinstance(ret[key], np.ndarray) and not ret[key].shape:\n ret[key] = ret[key].tolist()\n #print 'done'\n return ret", "response": "Loads the requested variables from the matlab shell."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the named groups in a regular expression compiled or as string", "response": "def rexGroups(rex):\n \"\"\"Return the named groups in a regular expression (compiled or as string)\n in occuring order.\n\n >>> rexGroups(r'(?P\n
\n {% endactiveurl %}\n in this case is valid content root tag\n ''')\n return content", "response": "check content for active urls"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef render_content(content, **kwargs):\n '''check content for \"active\" urls, store results to django cache'''\n # try to take pre rendered content from django cache, if caching is enabled\n if settings.ACTIVE_URL_CACHE:\n cache_key = get_cache_key(content, **kwargs)\n\n # get cached content from django cache backend\n from_cache = cache.get(cache_key)\n\n # return pre rendered content if it exist in cache\n if from_cache is not None:\n return from_cache\n\n # render content with \"active\" logic\n content = check_content(content, **kwargs)\n\n # write rendered content to django cache backend, if caching is enabled\n if settings.ACTIVE_URL_CACHE:\n cache.set(cache_key, content, settings.ACTIVE_URL_CACHE_TIMEOUT)\n\n return content", "response": "check content for active urls store results to django cache"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nloading configuration merge with default settings", "response": "def load_configuration(self, **kwargs):\n '''load configuration, merge with default settings'''\n # update passed arguments with default values\n for key in settings.ACTIVE_URL_KWARGS:\n kwargs.setdefault(key, settings.ACTIVE_URL_KWARGS[key])\n\n # \"active\" html tag css class\n self.css_class = kwargs['css_class']\n # \"active\" html tag\n self.parent_tag = kwargs['parent_tag']\n # flipper for menu support\n self.menu = kwargs['menu']\n # whether to ignore / chomp get_params\n self.ignore_params = kwargs['ignore_params']"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _parse_response(response, clazz, is_list=False, resource_name=None):\n target = response.json()[\n resource_name] if resource_name else response.json()\n if is_list:\n return [clazz.from_json(resource) for resource in target]\n else:\n return clazz.from_json(target)", "response": "Parse a Marathon response into an object or list of objects."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nperform a request to the Marathon server.", "response": "def _do_request(self, method, path, params=None, data=None):\n \"\"\"Query Marathon server.\"\"\"\n headers = {\n 'Content-Type': 'application/json', 'Accept': 'application/json'}\n\n if self.auth_token:\n headers['Authorization'] = \"token={}\".format(self.auth_token)\n\n response = None\n servers = list(self.servers)\n while servers and response is None:\n server = servers.pop(0)\n url = ''.join([server.rstrip('/'), path])\n try:\n response = self.session.request(\n method, url, params=params, data=data, headers=headers,\n auth=self.auth, timeout=self.timeout, verify=self.verify)\n marathon.log.info('Got response from %s', server)\n except requests.exceptions.RequestException as e:\n marathon.log.error(\n 'Error while calling %s: %s', url, str(e))\n\n if response is None:\n raise NoResponseError('No remaining Marathon servers to try')\n\n if response.status_code >= 500:\n marathon.log.error('Got HTTP {code}: {body}'.format(\n code=response.status_code, body=response.text.encode('utf-8')))\n raise InternalServerError(response)\n elif response.status_code >= 400:\n marathon.log.error('Got HTTP {code}: {body}'.format(\n code=response.status_code, body=response.text.encode('utf-8')))\n if response.status_code == 404:\n raise NotFoundError(response)\n elif response.status_code == 409:\n raise ConflictError(response)\n else:\n raise MarathonHttpError(response)\n elif response.status_code >= 300:\n marathon.log.warn('Got HTTP {code}: {body}'.format(\n code=response.status_code, body=response.text.encode('utf-8')))\n else:\n marathon.log.debug('Got HTTP {code}: {body}'.format(\n code=response.status_code, body=response.text.encode('utf-8')))\n\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _do_sse_request(self, path, params=None):\n urls = [''.join([server.rstrip('/'), path]) for server in self.servers]\n while urls:\n url = urls.pop()\n try:\n # Requests does not set the original Authorization header on cross origin\n # redirects. If set allow_redirects=True we may get a 401 response.\n response = self.sse_session.get(\n url,\n params=params,\n stream=True,\n headers={'Accept': 'text/event-stream'},\n auth=self.auth,\n verify=self.verify,\n allow_redirects=False\n )\n except Exception as e:\n marathon.log.error(\n 'Error while calling %s: %s', url, e.message)\n else:\n if response.is_redirect and response.next:\n urls.append(response.next.url)\n marathon.log.debug(\"Got redirect to {}\".format(response.next.url))\n elif response.ok:\n return response.iter_lines()\n\n raise MarathonError('No remaining Marathon servers to try')", "response": "Query Marathon server for events."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create_app(self, app_id, app, minimal=True):\n app.id = app_id\n data = app.to_json(minimal=minimal)\n response = self._do_request('POST', '/v2/apps', data=data)\n if response.status_code == 201:\n return self._parse_response(response, MarathonApp)\n else:\n return False", "response": "Create and start an app."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef list_apps(self, cmd=None, embed_tasks=False, embed_counts=False,\n embed_deployments=False, embed_readiness=False,\n embed_last_task_failure=False, embed_failures=False,\n embed_task_stats=False, app_id=None, label=None, **kwargs):\n \"\"\"List all apps.\n\n :param str cmd: if passed, only show apps with a matching `cmd`\n :param bool embed_tasks: embed tasks in result\n :param bool embed_counts: embed all task counts\n :param bool embed_deployments: embed all deployment identifier\n :param bool embed_readiness: embed all readiness check results\n :param bool embed_last_task_failure: embeds the last task failure\n :param bool embed_failures: shorthand for embed_last_task_failure\n :param bool embed_task_stats: embed task stats in result\n :param str app_id: if passed, only show apps with an 'id' that matches or contains this value\n :param str label: if passed, only show apps with the selected labels\n :param kwargs: arbitrary search filters\n\n :returns: list of applications\n :rtype: list[:class:`marathon.models.app.MarathonApp`]\n \"\"\"\n params = {}\n if cmd:\n params['cmd'] = cmd\n if app_id:\n params['id'] = app_id\n if label:\n params['label'] = label\n\n embed_params = {\n 'app.tasks': embed_tasks,\n 'app.counts': embed_counts,\n 'app.deployments': embed_deployments,\n 'app.readiness': embed_readiness,\n 'app.lastTaskFailure': embed_last_task_failure,\n 'app.failures': embed_failures,\n 'app.taskStats': embed_task_stats\n }\n filtered_embed_params = [k for (k, v) in embed_params.items() if v]\n if filtered_embed_params:\n params['embed'] = filtered_embed_params\n\n response = self._do_request('GET', '/v2/apps', params=params)\n apps = self._parse_response(\n response, MarathonApp, is_list=True, resource_name='apps')\n for k, v in kwargs.items():\n apps = [o for o in apps if getattr(o, k) == v]\n return apps", "response": "List all apps in the Marathon system."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nget a single application.", "response": "def get_app(self, app_id, embed_tasks=False, embed_counts=False,\n embed_deployments=False, embed_readiness=False,\n embed_last_task_failure=False, embed_failures=False,\n embed_task_stats=False):\n \"\"\"Get a single app.\n\n :param str app_id: application ID\n :param bool embed_tasks: embed tasks in result\n :param bool embed_counts: embed all task counts\n :param bool embed_deployments: embed all deployment identifier\n :param bool embed_readiness: embed all readiness check results\n :param bool embed_last_task_failure: embeds the last task failure\n :param bool embed_failures: shorthand for embed_last_task_failure\n :param bool embed_task_stats: embed task stats in result\n\n :returns: application\n :rtype: :class:`marathon.models.app.MarathonApp`\n \"\"\"\n params = {}\n embed_params = {\n 'app.tasks': embed_tasks,\n 'app.counts': embed_counts,\n 'app.deployments': embed_deployments,\n 'app.readiness': embed_readiness,\n 'app.lastTaskFailure': embed_last_task_failure,\n 'app.failures': embed_failures,\n 'app.taskStats': embed_task_stats\n }\n filtered_embed_params = [k for (k, v) in embed_params.items() if v]\n if filtered_embed_params:\n params['embed'] = filtered_embed_params\n\n response = self._do_request(\n 'GET', '/v2/apps/{app_id}'.format(app_id=app_id), params=params)\n return self._parse_response(response, MarathonApp, resource_name='app')"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nupdate an app. Applies writable settings in `app` to `app_id` Note: this method can not be used to rename apps. :param str app_id: target application ID :param app: application settings :type app: :class:`marathon.models.app.MarathonApp` :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict", "response": "def update_app(self, app_id, app, force=False, minimal=True):\n \"\"\"Update an app.\n\n Applies writable settings in `app` to `app_id`\n Note: this method can not be used to rename apps.\n\n :param str app_id: target application ID\n :param app: application settings\n :type app: :class:`marathon.models.app.MarathonApp`\n :param bool force: apply even if a deployment is in progress\n :param bool minimal: ignore nulls and empty collections\n\n :returns: a dict containing the deployment id and version\n :rtype: dict\n \"\"\"\n # Changes won't take if version is set - blank it for convenience\n app.version = None\n\n params = {'force': force}\n data = app.to_json(minimal=minimal)\n\n response = self._do_request(\n 'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data)\n return response.json()"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nupdates multiple apps. Applies writable settings in elements of apps either by upgrading existing ones or creating new ones :param apps: sequence of application settings :param bool force: apply even if a deployment is in progress :param bool minimal: ignore nulls and empty collections :returns: a dict containing the deployment id and version :rtype: dict", "response": "def update_apps(self, apps, force=False, minimal=True):\n \"\"\"Update multiple apps.\n\n Applies writable settings in elements of apps either by upgrading existing ones or creating new ones\n\n :param apps: sequence of application settings\n :param bool force: apply even if a deployment is in progress\n :param bool minimal: ignore nulls and empty collections\n\n :returns: a dict containing the deployment id and version\n :rtype: dict\n \"\"\"\n json_repr_apps = []\n for app in apps:\n # Changes won't take if version is set - blank it for convenience\n app.version = None\n json_repr_apps.append(app.json_repr(minimal=minimal))\n\n params = {'force': force}\n encoder = MarathonMinimalJsonEncoder if minimal else MarathonJsonEncoder\n data = json.dumps(json_repr_apps, cls=encoder, sort_keys=True)\n\n response = self._do_request(\n 'PUT', '/v2/apps', params=params, data=data)\n return response.json()"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef rollback_app(self, app_id, version, force=False):\n params = {'force': force}\n data = json.dumps({'version': version})\n response = self._do_request(\n 'PUT', '/v2/apps/{app_id}'.format(app_id=app_id), params=params, data=data)\n return response.json()", "response": "Roll an app back to a previous version."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef delete_app(self, app_id, force=False):\n params = {'force': force}\n response = self._do_request(\n 'DELETE', '/v2/apps/{app_id}'.format(app_id=app_id), params=params)\n return response.json()", "response": "Stop and destroy an application."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef scale_app(self, app_id, instances=None, delta=None, force=False):\n if instances is None and delta is None:\n marathon.log.error('instances or delta must be passed')\n return\n\n try:\n app = self.get_app(app_id)\n except NotFoundError:\n marathon.log.error('App \"{app}\" not found'.format(app=app_id))\n return\n\n desired = instances if instances is not None else (\n app.instances + delta)\n return self.update_app(app.id, MarathonApp(instances=desired), force=force)", "response": "Scale an app to a target number of instances or by some delta."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncreating and start a group.", "response": "def create_group(self, group):\n \"\"\"Create and start a group.\n\n :param :class:`marathon.models.group.MarathonGroup` group: the group to create\n\n :returns: success\n :rtype: dict containing the version ID\n \"\"\"\n data = group.to_json()\n response = self._do_request('POST', '/v2/groups', data=data)\n return response.json()"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nlists all groups. :param kwargs: arbitrary search filters :returns: list of groups :rtype: list[:class:`marathon.models.group.MarathonGroup`]", "response": "def list_groups(self, **kwargs):\n \"\"\"List all groups.\n\n :param kwargs: arbitrary search filters\n\n :returns: list of groups\n :rtype: list[:class:`marathon.models.group.MarathonGroup`]\n \"\"\"\n response = self._do_request('GET', '/v2/groups')\n groups = self._parse_response(\n response, MarathonGroup, is_list=True, resource_name='groups')\n for k, v in kwargs.items():\n groups = [o for o in groups if getattr(o, k) == v]\n return groups"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nget a single group.", "response": "def get_group(self, group_id):\n \"\"\"Get a single group.\n\n :param str group_id: group ID\n\n :returns: group\n :rtype: :class:`marathon.models.group.MarathonGroup`\n \"\"\"\n response = self._do_request(\n 'GET', '/v2/groups/{group_id}'.format(group_id=group_id))\n return self._parse_response(response, MarathonGroup)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nupdating a group s internal cache entries.", "response": "def update_group(self, group_id, group, force=False, minimal=True):\n \"\"\"Update a group.\n\n Applies writable settings in `group` to `group_id`\n Note: this method can not be used to rename groups.\n\n :param str group_id: target group ID\n :param group: group settings\n :type group: :class:`marathon.models.group.MarathonGroup`\n :param bool force: apply even if a deployment is in progress\n :param bool minimal: ignore nulls and empty collections\n\n :returns: a dict containing the deployment id and version\n :rtype: dict\n \"\"\"\n # Changes won't take if version is set - blank it for convenience\n group.version = None\n\n params = {'force': force}\n data = group.to_json(minimal=minimal)\n\n response = self._do_request(\n 'PUT', '/v2/groups/{group_id}'.format(group_id=group_id), data=data, params=params)\n return response.json()"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nrolls a group back to a previous version.", "response": "def rollback_group(self, group_id, version, force=False):\n \"\"\"Roll a group back to a previous version.\n\n :param str group_id: group ID\n :param str version: group version\n :param bool force: apply even if a deployment is in progress\n\n :returns: a dict containing the deployment id and version\n :rtype: dict\n \"\"\"\n params = {'force': force}\n response = self._do_request(\n 'PUT',\n '/v2/groups/{group_id}/versions/{version}'.format(\n group_id=group_id, version=version),\n params=params)\n return response.json()"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nstops and destroy a group.", "response": "def delete_group(self, group_id, force=False):\n \"\"\"Stop and destroy a group.\n\n :param str group_id: group ID\n :param bool force: apply even if a deployment is in progress\n\n :returns: a dict containing the deleted version\n :rtype: dict\n \"\"\"\n params = {'force': force}\n response = self._do_request(\n 'DELETE', '/v2/groups/{group_id}'.format(group_id=group_id), params=params)\n return response.json()"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef scale_group(self, group_id, scale_by):\n data = {'scaleBy': scale_by}\n response = self._do_request(\n 'PUT', '/v2/groups/{group_id}'.format(group_id=group_id), data=json.dumps(data))\n return response.json()", "response": "Scale a group by a factor."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef list_tasks(self, app_id=None, **kwargs):\n response = self._do_request(\n 'GET', '/v2/apps/%s/tasks' % app_id if app_id else '/v2/tasks')\n tasks = self._parse_response(\n response, MarathonTask, is_list=True, resource_name='tasks')\n [setattr(t, 'app_id', app_id)\n for t in tasks if app_id and t.app_id is None]\n for k, v in kwargs.items():\n tasks = [o for o in tasks if getattr(o, k) == v]\n\n return tasks", "response": "List running tasks optionally filtered by app_id."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef kill_given_tasks(self, task_ids, scale=False, force=None):\n params = {'scale': scale}\n if force is not None:\n params['force'] = force\n data = json.dumps({\"ids\": task_ids})\n response = self._do_request(\n 'POST', '/v2/tasks/delete', params=params, data=data)\n return response == 200", "response": "Kill a list of given tasks."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef kill_tasks(self, app_id, scale=False, wipe=False,\n host=None, batch_size=0, batch_delay=0):\n \"\"\"Kill all tasks belonging to app.\n\n :param str app_id: application ID\n :param bool scale: if true, scale down the app by the number of tasks killed\n :param str host: if provided, only terminate tasks on this Mesos slave\n :param int batch_size: if non-zero, terminate tasks in groups of this size\n :param int batch_delay: time (in seconds) to wait in between batched kills. If zero, automatically determine\n\n :returns: list of killed tasks\n :rtype: list[:class:`marathon.models.task.MarathonTask`]\n \"\"\"\n def batch(iterable, size):\n sourceiter = iter(iterable)\n while True:\n batchiter = itertools.islice(sourceiter, size)\n yield itertools.chain([next(batchiter)], batchiter)\n\n if batch_size == 0:\n # Terminate all at once\n params = {'scale': scale, 'wipe': wipe}\n if host:\n params['host'] = host\n response = self._do_request(\n 'DELETE', '/v2/apps/{app_id}/tasks'.format(app_id=app_id), params)\n # Marathon is inconsistent about what type of object it returns on the multi\n # task deletion endpoint, depending on the version of Marathon. See:\n # https://github.com/mesosphere/marathon/blob/06a6f763a75fb6d652b4f1660685ae234bd15387/src/main/scala/mesosphere/marathon/api/v2/AppTasksResource.scala#L88-L95\n if \"tasks\" in response.json():\n return self._parse_response(response, MarathonTask, is_list=True, resource_name='tasks')\n else:\n return response.json()\n else:\n # Terminate in batches\n tasks = self.list_tasks(\n app_id, host=host) if host else self.list_tasks(app_id)\n for tbatch in batch(tasks, batch_size):\n killed_tasks = [self.kill_task(app_id, t.id, scale=scale, wipe=wipe)\n for t in tbatch]\n\n # Pause until the tasks have been killed to avoid race\n # conditions\n killed_task_ids = set(t.id for t in killed_tasks)\n running_task_ids = killed_task_ids\n while killed_task_ids.intersection(running_task_ids):\n time.sleep(1)\n running_task_ids = set(\n t.id for t in self.get_app(app_id).tasks)\n\n if batch_delay == 0:\n # Pause until the replacement tasks are healthy\n desired_instances = self.get_app(app_id).instances\n running_instances = 0\n while running_instances < desired_instances:\n time.sleep(1)\n running_instances = sum(\n t.started_at is None for t in self.get_app(app_id).tasks)\n else:\n time.sleep(batch_delay)\n\n return tasks", "response": "Kill all tasks belonging to an app."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef kill_task(self, app_id, task_id, scale=False, wipe=False):\n params = {'scale': scale, 'wipe': wipe}\n response = self._do_request('DELETE', '/v2/apps/{app_id}/tasks/{task_id}'\n .format(app_id=app_id, task_id=task_id), params)\n # Marathon is inconsistent about what type of object it returns on the multi\n # task deletion endpoint, depending on the version of Marathon. See:\n # https://github.com/mesosphere/marathon/blob/06a6f763a75fb6d652b4f1660685ae234bd15387/src/main/scala/mesosphere/marathon/api/v2/AppTasksResource.scala#L88-L95\n if \"task\" in response.json():\n return self._parse_response(response, MarathonTask, is_list=False, resource_name='task')\n else:\n return response.json()", "response": "Kill a task.\n\n :param str app_id: application ID\n :param str task_id: the task to kill\n :param bool scale: if true, scale down the app by one if the task exists\n\n :returns: the killed task\n :rtype: :class:`marathon.models.task.MarathonTask`"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef list_versions(self, app_id):\n response = self._do_request(\n 'GET', '/v2/apps/{app_id}/versions'.format(app_id=app_id))\n return [version for version in response.json()['versions']]", "response": "List the versions of an app."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_version(self, app_id, version):\n response = self._do_request('GET', '/v2/apps/{app_id}/versions/{version}'\n .format(app_id=app_id, version=version))\n return MarathonApp.from_json(response.json())", "response": "Get the configuration of an app at a specific version."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef create_event_subscription(self, url):\n params = {'callbackUrl': url}\n response = self._do_request('POST', '/v2/eventSubscriptions', params)\n return response.json()", "response": "Register a callback URL as an event subscriber."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nlist all running deployments.", "response": "def list_deployments(self):\n \"\"\"List all running deployments.\n\n :returns: list of deployments\n :rtype: list[:class:`marathon.models.deployment.MarathonDeployment`]\n \"\"\"\n response = self._do_request('GET', '/v2/deployments')\n return self._parse_response(response, MarathonDeployment, is_list=True)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef list_queue(self, embed_last_unused_offers=False):\n if embed_last_unused_offers:\n params = {'embed': 'lastUnusedOffers'}\n else:\n params = {}\n response = self._do_request('GET', '/v2/queue', params=params)\n return self._parse_response(response, MarathonQueueItem, is_list=True, resource_name='queue')", "response": "List all the tasks queued up or waiting to be scheduled."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ncancel a deployment. :param str deployment_id: deployment id :param bool force: if true, don't create a rollback deployment to restore the previous configuration :returns: a dict containing the deployment id and version (empty dict if force=True) :rtype: dict", "response": "def delete_deployment(self, deployment_id, force=False):\n \"\"\"Cancel a deployment.\n\n :param str deployment_id: deployment id\n :param bool force: if true, don't create a rollback deployment to restore the previous configuration\n\n :returns: a dict containing the deployment id and version (empty dict if force=True)\n :rtype: dict\n \"\"\"\n if force:\n params = {'force': True}\n self._do_request('DELETE', '/v2/deployments/{deployment}'.format(\n deployment=deployment_id), params=params)\n # Successful DELETE with ?force=true returns empty text (and status\n # code 202). Client code should poll until deployment is removed.\n return {}\n else:\n response = self._do_request(\n 'DELETE', '/v2/deployments/{deployment}'.format(deployment=deployment_id))\n return response.json()"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef event_stream(self, raw=False, event_types=None):\n\n ef = EventFactory()\n\n params = {\n 'event_type': [\n EventFactory.class_to_event[et] if isinstance(\n et, type) and issubclass(et, MarathonEvent) else et\n for et in event_types or []\n ]\n }\n\n for raw_message in self._do_sse_request('/v2/events', params=params):\n try:\n _data = raw_message.decode('utf8').split(':', 1)\n\n if _data[0] == 'data':\n if raw:\n yield _data[1]\n else:\n event_data = json.loads(_data[1].strip())\n if 'eventType' not in event_data:\n raise MarathonError('Invalid event data received.')\n yield ef.process(event_data)\n except ValueError:\n raise MarathonError('Invalid event data received.')", "response": "Polls event bus using / v2 / events"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nchecks if a path is a correct format that Marathon expects. Raises ValueError if not valid.", "response": "def assert_valid_path(path):\n \"\"\"Checks if a path is a correct format that Marathon expects. Raises ValueError if not valid.\n\n :param str path: The app id.\n\n :rtype: str\n \"\"\"\n if path is None:\n return\n # As seen in:\n # https://github.com/mesosphere/marathon/blob/0c11661ca2f259f8a903d114ef79023649a6f04b/src/main/scala/mesosphere/marathon/state/PathId.scala#L71\n for id in filter(None, path.strip('/').split('/')):\n if not ID_PATTERN.match(id):\n raise ValueError(\n 'invalid path (allowed: lowercase letters, digits, hyphen, \"/\", \".\", \"..\"): %r' % path)\n return path"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef assert_valid_id(id):\n if id is None:\n return\n if not ID_PATTERN.match(id.strip('/')):\n raise ValueError(\n 'invalid id (allowed: lowercase letters, digits, hyphen, \".\", \"..\"): %r' % id)\n return id", "response": "Checks if an id is the correct format that Marathon expects. Raises ValueError if not valid."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nconstructs a JSON - friendly representation of the object.", "response": "def json_repr(self, minimal=False):\n \"\"\"Construct a JSON-friendly representation of the object.\n\n :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections)\n\n :rtype: dict\n \"\"\"\n if minimal:\n return {to_camel_case(k): v for k, v in vars(self).items() if (v or v is False or v == 0)}\n else:\n return {to_camel_case(k): v for k, v in vars(self).items()}"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nconstructs an object from a parsed response.", "response": "def from_json(cls, attributes):\n \"\"\"Construct an object from a parsed response.\n\n :param dict attributes: object attributes from parsed response\n \"\"\"\n return cls(**{to_snake_case(k): v for k, v in attributes.items()})"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nencoding an object as a JSON string.", "response": "def to_json(self, minimal=True):\n \"\"\"Encode an object as a JSON string.\n\n :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections)\n\n :rtype: str\n \"\"\"\n if minimal:\n return json.dumps(self.json_repr(minimal=True), cls=MarathonMinimalJsonEncoder, sort_keys=True)\n else:\n return json.dumps(self.json_repr(), cls=MarathonJsonEncoder, sort_keys=True)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef json_repr(self, minimal=False):\n if self.value:\n return [self.field, self.operator, self.value]\n else:\n return [self.field, self.operator]", "response": "Construct a JSON - friendly representation of the object."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nconstructing a MarathonConstraint from a parsed response.", "response": "def from_json(cls, obj):\n \"\"\"Construct a MarathonConstraint from a parsed response.\n\n :param dict attributes: object attributes from parsed response\n\n :rtype: :class:`MarathonConstraint`\n \"\"\"\n if len(obj) == 2:\n (field, operator) = obj\n return cls(field, operator)\n if len(obj) > 2:\n (field, operator, value) = obj\n return cls(field, operator, value)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef from_string(cls, constraint):\n obj = constraint.split(':')\n marathon_constraint = cls.from_json(obj)\n\n if marathon_constraint:\n return marathon_constraint\n\n raise ValueError(\"Invalid string format. \"\n \"Expected `field:operator:value`\")", "response": "Returns a MarathonResource object from a string representation of a MarathonConstraint."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef from_tasks(cls, tasks):\n\n endpoints = [\n [\n MarathonEndpoint(task.app_id, task.service_ports[\n port_index], task.host, task.id, port)\n for port_index, port in enumerate(task.ports)\n ]\n for task in tasks\n ]\n # Flatten result\n return [item for sublist in endpoints for item in sublist]", "response": "Construct a list of MarathonEndpoints from a list of tasks."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _format_newlines(prefix, formatted_node, options):\n replacement = u''.join([\n options.NEWLINE,\n u'\\n',\n prefix])\n return formatted_node.replace(u'\\n', replacement)", "response": "Convert newlines into U + 23EC characters followed by an actual newline and a tree prefix."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nget a band with the specified tag.", "response": "def get_band(self, tag):\n \"\"\"Gets a band.\n\n Gets a band with specified tag. If no tag is specified, the request will fail.\n If the tag is invalid, a brawlstars.InvalidTag will be raised.\n If the data is missing, a ValueError will be raised.\n If the connection times out, a brawlstars.Timeout will be raised.\n If the data was unable to be received, a brawlstars.HTTPError will be raised along with the\n HTTP status code.\n On success, will return a Band.\n \"\"\"\n\n tag = tag.strip(\"#\")\n tag = tag.upper()\n\n try:\n resp = requests.get(self._base_url + 'bands/' + tag, headers=self.headers, timeout=self.timeout)\n if resp.status_code == 200:\n data = resp.json()\n elif 500 > resp.status_code > 400:\n raise HTTPError(resp.status_code)\n else:\n raise Error()\n except ValueError:\n raise MissingData('data')\n except Exception:\n raise Timeout()\n\n data = Box(data)\n band = Band(data)\n return band"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def get_player(self, tag):\n\n tag = tag.strip(\"#\")\n tag = tag.upper()\n\n try:\n async with self.session.get(self._base_url + 'players/' + tag, timeout=self.timeout,\n headers=self.headers) as resp:\n if resp.status == 200:\n data = await resp.json()\n elif 500 > resp.status > 400:\n raise HTTPError(resp.status)\n else:\n raise Error()\n except asyncio.TimeoutError:\n raise Timeout()\n except ValueError:\n raise MissingData('data')\n except Exception:\n raise InvalidArg('tag')\n\n data = Box(data)\n player = Player(data)\n return player", "response": "Gets a player with specified tag."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\nasync def get_band(self, tag):\n\n tag = tag.strip(\"#\")\n tag = tag.upper()\n\n try:\n async with self.session.get(self._base_url + 'bands/' + tag, timeout=self.timeout,\n headers=self.headers) as resp:\n if resp.status == 200:\n data = await resp.json()\n elif 500 > resp.status > 400:\n raise HTTPError(resp.status)\n else:\n raise Error()\n except asyncio.TimeoutError:\n raise Timeout()\n except ValueError:\n raise MissingData('data')\n except Exception:\n raise InvalidArg('tag')\n\n data = Box(data)\n band = Band(data)\n return band", "response": "Gets a band with the specified tag."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef lazy_module(modname, error_strings=None, lazy_mod_class=LazyModule,\n level='leaf'):\n \"\"\"Function allowing lazy importing of a module into the namespace.\n\n A lazy module object is created, registered in `sys.modules`, and\n returned. This is a hollow module; actual loading, and `ImportErrors` if\n not found, are delayed until an attempt is made to access attributes of the\n lazy module.\n\n A handy application is to use :func:`lazy_module` early in your own code\n (say, in `__init__.py`) to register all modulenames you want to be lazy.\n Because of registration in `sys.modules` later invocations of\n `import modulename` will also return the lazy object. This means that after\n initial registration the rest of your code can use regular pyhon import\n statements and retain the lazyness of the modules.\n\n Parameters\n ----------\n modname : str\n The module to import.\n error_strings : dict, optional\n A dictionary of strings to use when module-loading fails. Key 'msg'\n sets the message to use (defaults to :attr:`lazy_import._MSG`). The\n message is formatted using the remaining dictionary keys. The default\n message informs the user of which module is missing (key 'module'),\n what code loaded the module as lazy (key 'caller'), and which package\n should be installed to solve the dependency (key 'install_name').\n None of the keys is mandatory and all are given smart names by default.\n lazy_mod_class: type, optional\n Which class to use when instantiating the lazy module, to allow\n deep customization. The default is :class:`LazyModule` and custom\n alternatives **must** be a subclass thereof.\n level : str, optional\n Which submodule reference to return. Either a reference to the 'leaf'\n module (the default) or to the 'base' module. This is useful if you'll\n be using the module functionality in the same place you're calling\n :func:`lazy_module` from, since then you don't need to run `import`\n again. Setting *level* does not affect which names/modules get\n registered in `sys.modules`.\n For *level* set to 'base' and *modulename* 'aaa.bbb.ccc'::\n\n aaa = lazy_import.lazy_module(\"aaa.bbb.ccc\", level='base')\n # 'aaa' becomes defined in the current namespace, with\n # (sub)attributes 'aaa.bbb' and 'aaa.bbb.ccc'.\n # It's the lazy equivalent to:\n import aaa.bbb.ccc\n\n For *level* set to 'leaf'::\n\n ccc = lazy_import.lazy_module(\"aaa.bbb.ccc\", level='leaf')\n # Only 'ccc' becomes set in the current namespace.\n # Lazy equivalent to:\n from aaa.bbb import ccc\n\n Returns\n -------\n module\n The module specified by *modname*, or its base, depending on *level*.\n The module isn't immediately imported. Instead, an instance of\n *lazy_mod_class* is returned. Upon access to any of its attributes, the\n module is finally loaded.\n\n Examples\n --------\n >>> import lazy_import, sys\n >>> np = lazy_import.lazy_module(\"numpy\")\n >>> np\n Lazily-loaded module numpy\n >>> np is sys.modules['numpy']\n True\n >>> np.pi # This causes the full loading of the module ...\n 3.141592653589793\n >>> np # ... and the module is changed in place. \n
\")\n return mark_safe(\"%s\" % html)", "response": "Pretty - print the JSON data."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef addHelpMenu(menuName, parentMenuFunction=None):\n '''\n Adds a help menu to the plugin menu.\n This method should be called from the initGui() method of the plugin\n\n :param menuName: The name of the plugin menu in which the about menu is to be added.\n '''\n\n parentMenuFunction = parentMenuFunction or iface.addPluginToMenu\n namespace = _callerName().split(\".\")[0]\n path = \"file://{}\".format(os.path.join(os.path.dirname(_callerPath()), \"docs\", \"html\", \"index.html\")) \n helpAction = QtWidgets.QAction(QgsApplication.getThemeIcon('/mActionHelpContents.svg'), \n \"Plugin help...\", iface.mainWindow())\n helpAction.setObjectName(namespace + \"help\")\n helpAction.triggered.connect(lambda: openHelp(path))\n parentMenuFunction(menuName, helpAction)\n global _helpActions\n _helpActions[menuName] = helpAction", "response": "Adds a help menu to the plugin menu."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef addAboutMenu(menuName, parentMenuFunction=None):\n '''\n Adds an 'about...' menu to the plugin menu.\n This method should be called from the initGui() method of the plugin\n\n :param menuName: The name of the plugin menu in which the about menu is to be added\n '''\n\n parentMenuFunction = parentMenuFunction or iface.addPluginToMenu\n namespace = _callerName().split(\".\")[0]\n icon = QtGui.QIcon(os.path.join(os.path.dirname(os.path.dirname(__file__)), \"icons\", \"help.png\"))\n aboutAction = QtWidgets.QAction(icon, \"About...\", iface.mainWindow())\n aboutAction.setObjectName(namespace + \"about\")\n aboutAction.triggered.connect(lambda: openAboutDialog(namespace))\n parentMenuFunction(menuName, aboutAction)\n global _aboutActions\n _aboutActions[menuName] = aboutAction", "response": "Adds an about menu to the plugin menu."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef showMessageDialog(title, text):\n '''\n Show a dialog containing a given text, with a given title.\n\n The text accepts HTML syntax\n '''\n dlg = QgsMessageOutput.createMessageOutput()\n dlg.setTitle(title)\n dlg.setMessage(text, QgsMessageOutput.MessageHtml)\n dlg.showMessage()", "response": "Show a dialog containing a given text with a given title."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef askForFiles(parent, msg = None, isSave = False, allowMultiple = False, exts = \"*\"):\n '''\n Asks for a file or files, opening the corresponding dialog with the last path that was selected\n when this same function was invoked from the calling method.\n\n :param parent: The parent window\n :param msg: The message to use for the dialog title\n :param isSave: true if we are asking for file to save\n :param allowMultiple: True if should allow multiple files to be selected. Ignored if isSave == True\n :param exts: Extensions to allow in the file dialog. Can be a single string or a list of them.\n Use \"*\" to add an option that allows all files to be selected\n\n :returns: A string with the selected filepath or an array of them, depending on whether allowMultiple is True of False\n '''\n msg = msg or 'Select file'\n caller = _callerName().split(\".\")\n name = \"/\".join([LAST_PATH, caller[-1]])\n namespace = caller[0]\n path = pluginSetting(name, namespace)\n f = None\n if not isinstance(exts, list):\n exts = [exts]\n extString = \";; \".join([\" %s files (*.%s)\" % (e.upper(), e) if e != \"*\" else \"All files (*.*)\" for e in exts])\n if allowMultiple:\n ret = QtWidgets.QFileDialog.getOpenFileNames(parent, msg, path, '*.' + extString)\n if ret:\n f = ret[0]\n else:\n f = ret = None\n else:\n if isSave:\n ret = QtWidgets.QFileDialog.getSaveFileName(parent, msg, path, '*.' + extString) or None\n if ret is not None and not ret.endswith(exts[0]):\n ret += \".\" + exts[0]\n else:\n ret = QtWidgets.QFileDialog.getOpenFileName(parent, msg , path, '*.' + extString) or None\n f = ret\n\n if f is not None:\n setPluginSetting(name, os.path.dirname(f), namespace)\n\n return ret", "response": "Asks for a file or files in the current directory of the current directory."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nasking for a folder opening the corresponding dialog with the last path that was selected by the calling function.", "response": "def askForFolder(parent, msg = None):\n '''\n Asks for a folder, opening the corresponding dialog with the last path that was selected\n when this same function was invoked from the calling method\n\n :param parent: The parent window\n :param msg: The message to use for the dialog title\n '''\n msg = msg or 'Select folder'\n caller = _callerName().split(\".\")\n name = \"/\".join([LAST_PATH, caller[-1]])\n namespace = caller[0]\n path = pluginSetting(name, namespace)\n folder = QtWidgets.QFileDialog.getExistingDirectory(parent, msg, path)\n if folder:\n setPluginSetting(name, folder, namespace)\n return folder"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef execute(func, message = None):\n '''\n Executes a lengthy tasks in a separate thread and displays a waiting dialog if needed.\n Sets the cursor to wait cursor while the task is running.\n\n This function does not provide any support for progress indication\n\n :param func: The function to execute.\n\n :param message: The message to display in the wait dialog. If not passed, the dialog won't be shown\n '''\n global _dialog\n cursor = QtWidgets.QApplication.overrideCursor()\n waitCursor = (cursor is not None and cursor.shape() == QtCore.Qt.WaitCursor)\n dialogCreated = False\n try:\n QtCore.QCoreApplication.processEvents()\n if not waitCursor:\n QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))\n if message is not None:\n t = ExecutorThread(func)\n loop = QtCore.QEventLoop()\n t.finished.connect(loop.exit, QtCore.Qt.QueuedConnection)\n if _dialog is None:\n dialogCreated = True\n _dialog = QtGui.QProgressDialog(message, \"Running\", 0, 0, iface.mainWindow())\n _dialog.setWindowTitle(\"Running\")\n _dialog.setWindowModality(QtCore.Qt.WindowModal);\n _dialog.setMinimumDuration(1000)\n _dialog.setMaximum(100)\n _dialog.setValue(0)\n _dialog.setMaximum(0)\n _dialog.setCancelButton(None)\n else:\n oldText = _dialog.labelText()\n _dialog.setLabelText(message)\n QtWidgets.QApplication.processEvents()\n t.start()\n loop.exec_(flags = QtCore.QEventLoop.ExcludeUserInputEvents)\n if t.exception is not None:\n raise t.exception\n return t.returnValue\n else:\n return func()\n finally:\n if message is not None:\n if dialogCreated:\n _dialog.reset()\n _dialog = None\n else:\n _dialog.setLabelText(oldText)\n if not waitCursor:\n QtWidgets.QApplication.restoreOverrideCursor()\n QtCore.QCoreApplication.processEvents()", "response": "Executes a function in a separate thread and displays a waiting dialog if needed."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nmaking a HTTP request to the server.", "response": "def request(self, url, method=\"GET\", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None, blocking=True):\n \"\"\"\n Make a network request by calling QgsNetworkAccessManager.\n redirections argument is ignored and is here only for httplib2 compatibility.\n \"\"\"\n self.msg_log(u'http_call request: {0}'.format(url))\n\n self.blocking_mode = blocking\n req = QNetworkRequest()\n # Avoid double quoting form QUrl\n url = urllib.parse.unquote(url)\n req.setUrl(QUrl(url))\n if headers is not None:\n # This fixes a wierd error with compressed content not being correctly\n # inflated.\n # If you set the header on the QNetworkRequest you are basically telling\n # QNetworkAccessManager \"I know what I'm doing, please don't do any content\n # encoding processing\".\n # See: https://bugs.webkit.org/show_bug.cgi?id=63696#c1\n try:\n del headers['Accept-Encoding']\n except KeyError:\n pass\n for k, v in list(headers.items()):\n self.msg_log(\"Setting header %s to %s\" % (k, v))\n req.setRawHeader(k.encode(), v.encode())\n if self.authid:\n self.msg_log(\"Update request w/ authid: {0}\".format(self.authid))\n self.auth_manager().updateNetworkRequest(req, self.authid)\n if self.reply is not None and self.reply.isRunning():\n self.reply.close()\n if method.lower() == 'delete':\n func = getattr(QgsNetworkAccessManager.instance(), 'deleteResource')\n else:\n func = getattr(QgsNetworkAccessManager.instance(), method.lower())\n # Calling the server ...\n # Let's log the whole call for debugging purposes:\n self.msg_log(\"Sending %s request to %s\" % (method.upper(), req.url().toString()))\n self.on_abort = False\n headers = {str(h): str(req.rawHeader(h)) for h in req.rawHeaderList()}\n for k, v in list(headers.items()):\n self.msg_log(\"%s: %s\" % (k, v))\n if method.lower() in ['post', 'put']:\n if isinstance(body, io.IOBase):\n body = body.read()\n if isinstance(body, str):\n body = body.encode()\n self.reply = func(req, body)\n else:\n self.reply = func(req)\n if self.authid:\n self.msg_log(\"Update reply w/ authid: {0}\".format(self.authid))\n self.auth_manager().updateNetworkReply(self.reply, self.authid)\n\n # necessary to trap local timout manage by QgsNetworkAccessManager\n # calling QgsNetworkAccessManager::abortRequest\n QgsNetworkAccessManager.instance().requestTimedOut.connect(self.requestTimedOut)\n\n self.reply.sslErrors.connect(self.sslErrors)\n self.reply.finished.connect(self.replyFinished)\n self.reply.downloadProgress.connect(self.downloadProgress)\n\n # block if blocking mode otherwise return immediatly\n # it's up to the caller to manage listeners in case of no blocking mode\n if not self.blocking_mode:\n return (None, None)\n\n # Call and block\n self.el = QEventLoop()\n self.reply.finished.connect(self.el.quit)\n\n # Catch all exceptions (and clean up requests)\n try:\n self.el.exec_(QEventLoop.ExcludeUserInputEvents)\n except Exception as e:\n raise e\n\n if self.reply:\n self.reply.finished.disconnect(self.el.quit)\n\n # emit exception in case of error\n if not self.http_call_result.ok:\n if self.http_call_result.exception and not self.exception_class:\n raise self.http_call_result.exception\n else:\n raise self.exception_class(self.http_call_result.reason)\n\n return (self.http_call_result, self.http_call_result.content)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef sslErrors(self, ssl_errors):\n if ssl_errors:\n for v in ssl_errors:\n self.msg_log(\"SSL Error: %s\" % v.errorString())\n if self.disable_ssl_certificate_validation:\n self.reply.ignoreSslErrors()", "response": "Handle SSL errors logging them if debug is on and ignoring them if disable_ssl_certificate_validation is set to True."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nabort the HTTP call.", "response": "def abort(self):\n \"\"\"\n Handle request to cancel HTTP call\n \"\"\"\n if (self.reply and self.reply.isRunning()):\n self.on_abort = True\n self.reply.abort()"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns all layers in a single key - value basis.", "response": "def mapLayers(name=None, types=None):\n \"\"\"\n Return all the loaded layers. Filters by name (optional) first and then type (optional)\n :param name: (optional) name of layer to return..\n :param type: (optional) The QgsMapLayer type of layer to return. Accepts a single value or a list of them\n :return: List of loaded layers. If name given will return all layers with matching name.\n \"\"\"\n if types is not None and not isinstance(types, list):\n types = [types]\n layers = _layerreg.mapLayers().values()\n _layers = []\n if name or types:\n if name:\n _layers = [layer for layer in layers if re.match(name, layer.name())]\n if types:\n _layers += [layer for layer in layers if layer.type() in types]\n return _layers\n else:\n return layers"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nadd a layer to the QGIS layer registry and session.", "response": "def addLayer(layer, loadInLegend=True):\n \"\"\"\n Add one or several layers to the QGIS session and layer registry.\n :param layer: The layer object or list with layers to add the QGIS layer registry and session.\n :param loadInLegend: True if this layer should be added to the legend.\n :return: The added layer\n \"\"\"\n if not hasattr(layer, \"__iter__\"):\n layer = [layer]\n _layerreg.addMapLayers(layer, loadInLegend)\n return layer"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nadding a layer from layer object but does not ask for CRS", "response": "def addLayerNoCrsDialog(layer, loadInLegend=True):\n '''\n Tries to add a layer from layer object\n Same as the addLayer method, but it does not ask for CRS, regardless of current\n configuration in QGIS settings\n '''\n settings = QSettings()\n prjSetting = settings.value('/Projections/defaultBehaviour')\n settings.setValue('/Projections/defaultBehaviour', '')\n # QGIS3\n prjSetting3 = settings.value('/Projections/defaultBehavior')\n settings.setValue('/Projections/defaultBehavior', '')\n layer = addLayer(layer, loadInLegend)\n settings.setValue('/Projections/defaultBehaviour', prjSetting)\n settings.setValue('/Projections/defaultBehavior', prjSetting3)\n return layer"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef newVectorLayer(filename, fields, geometryType, crs, encoding=\"utf-8\"):\n '''\n Creates a new vector layer\n\n :param filename: The filename to store the file. The extensions determines the type of file.\n If extension is not among the supported ones, a shapefile will be created and the file will\n get an added '.shp' to its path.\n If the filename is None, a memory layer will be created\n\n :param fields: the fields to add to the layer. Accepts a QgsFields object or a list of tuples (field_name, field_type)\n Accepted field types are basic Python types str, float, int and bool\n\n :param geometryType: The type of geometry of the layer to create.\n\n :param crs: The crs of the layer to create. Accepts a QgsCoordinateSystem object or a string with the CRS authId.\n\n :param encoding: The layer encoding\n '''\n if isinstance(crs, basestring):\n crs = QgsCoordinateReferenceSystem(crs)\n if filename is None:\n uri = GEOM_TYPE_MAP[geometryType]\n if crs.isValid():\n uri += '?crs=' + crs.authid() + '&'\n fieldsdesc = ['field=' + f for f in fields]\n\n fieldsstring = '&'.join(fieldsdesc)\n uri += fieldsstring\n layer = QgsVectorLayer(uri, \"mem_layer\", 'memory')\n else:\n formats = QgsVectorFileWriter.supportedFiltersAndFormats()\n OGRCodes = {}\n for (key, value) in formats.items():\n extension = unicode(key)\n extension = extension[extension.find('*.') + 2:]\n extension = extension[:extension.find(' ')]\n OGRCodes[extension] = value\n\n extension = os.path.splitext(filename)[1][1:]\n if extension not in OGRCodes:\n extension = 'shp'\n filename = filename + '.shp'\n\n if isinstance(fields, QgsFields):\n qgsfields = fields\n else:\n qgsfields = QgsFields()\n for field in fields:\n qgsfields.append(_toQgsField(field))\n\n QgsVectorFileWriter(filename, encoding, qgsfields,\n geometryType, crs, OGRCodes[extension])\n\n layer = QgsVectorLayer(filename, os.path.basename(filename), 'ogr')\n\n return layer", "response": "Create a new vector layer."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning the layer from the current project with the passed source Raises WrongLayerSourceException", "response": "def layerFromSource(source):\n '''\n Returns the layer from the current project with the passed source\n Raises WrongLayerSourceException if no layer with that source is found\n '''\n layers =_layerreg.mapLayers().values()\n for layer in layers:\n if layer.source() == source:\n return layer\n raise WrongLayerSourceException()"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ntries to load a layer from the given file and returns the layer object.", "response": "def loadLayer(filename, name = None, provider=None):\n '''\n Tries to load a layer from the given file\n\n :param filename: the path to the file to load.\n\n :param name: the name to use for adding the layer to the current project.\n If not passed or None, it will use the filename basename\n '''\n name = name or os.path.splitext(os.path.basename(filename))[0]\n if provider != 'gdal': # QGIS3 crashes if opening a raster as vector ... this needs further investigations\n qgslayer = QgsVectorLayer(filename, name, provider or \"ogr\")\n if provider == 'gdal' or not qgslayer.isValid():\n qgslayer = QgsRasterLayer(filename, name, provider or \"gdal\")\n if not qgslayer.isValid():\n raise RuntimeError('Could not load layer: ' + unicode(filename))\n\n return qgslayer"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ntries to load a layer from the given file and does not ask for CRS", "response": "def loadLayerNoCrsDialog(filename, name=None, provider=None):\n '''\n Tries to load a layer from the given file\n Same as the loadLayer method, but it does not ask for CRS, regardless of current\n configuration in QGIS settings\n '''\n settings = QSettings()\n prjSetting = settings.value('/Projections/defaultBehaviour')\n settings.setValue('/Projections/defaultBehaviour', '')\n # QGIS3:\n prjSetting3 = settings.value('/Projections/defaultBehavior')\n settings.setValue('/Projections/defaultBehavior', '')\n layer = loadLayer(filename, name, provider)\n settings.setValue('/Projections/defaultBehaviour', prjSetting)\n settings.setValue('/Projections/defaultBehavior', prjSetting3)\n return layer"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nadding a open settings menu to the plugin menu.", "response": "def addSettingsMenu(menuName, parentMenuFunction=None):\n '''\n Adds a 'open settings...' menu to the plugin menu.\n This method should be called from the initGui() method of the plugin\n\n :param menuName: The name of the plugin menu in which the settings menu is to be added\n :param parentMenuFunction: a function from QgisInterface to indicate where to put the container plugin menu.\n If not passed, it uses addPluginToMenu\n '''\n\n parentMenuFunction = parentMenuFunction or iface.addPluginToMenu\n namespace = _callerName().split(\".\")[0]\n settingsAction = QAction(\n QgsApplication.getThemeIcon('/mActionOptions.svg'),\n \"Plugin Settings...\",\n iface.mainWindow())\n settingsAction.setObjectName(namespace + \"settings\")\n settingsAction.triggered.connect(lambda: openSettingsDialog(namespace))\n parentMenuFunction(menuName, settingsAction)\n global _settingActions\n _settingActions[menuName] = settingsAction"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef openParametersDialog(params, title=None):\n '''\n Opens a dialog to enter parameters.\n Parameters are passed as a list of Parameter objects\n Returns a dict with param names as keys and param values as values\n Returns None if the dialog was cancelled\n '''\n QApplication.setOverrideCursor(QCursor(Qt.ArrowCursor))\n dlg = ParametersDialog(params, title)\n dlg.exec_()\n QApplication.restoreOverrideCursor()\n return dlg.values", "response": "Opens a dialog to enter parameters."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nruns do_index_command on each specified index and log the output.", "response": "def handle(self, *args, **options):\n \"\"\"Run do_index_command on each specified index and log the output.\"\"\"\n for index in options.pop(\"indexes\"):\n data = {}\n try:\n data = self.do_index_command(index, **options)\n except TransportError as ex:\n logger.warning(\"ElasticSearch threw an error: %s\", ex)\n data = {\"index\": index, \"status\": ex.status_code, \"reason\": ex.error}\n finally:\n logger.info(data)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncreates a new template.", "response": "def create(self, Name, Subject, HtmlBody=None, TextBody=None, Alias=None):\n \"\"\"\n Creates a template.\n\n :param Name: Name of template\n :param Subject: The content to use for the Subject when this template is used to send email.\n :param HtmlBody: The content to use for the HtmlBody when this template is used to send email.\n :param TextBody: The content to use for the HtmlBody when this template is used to send email.\n :return:\n \"\"\"\n assert TextBody or HtmlBody, \"Provide either email TextBody or HtmlBody or both\"\n data = {\"Name\": Name, \"Subject\": Subject, \"HtmlBody\": HtmlBody, \"TextBody\": TextBody, \"Alias\": Alias}\n return self._init_instance(self.call(\"POST\", \"/templates\", data=data))"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn a logger with the given name and verbosity and stream.", "response": "def get_logger(name, verbosity, stream):\n \"\"\"\n Returns simple console logger.\n \"\"\"\n logger = logging.getLogger(name)\n logger.setLevel(\n {0: DEFAULT_LOGGING_LEVEL, 1: logging.INFO, 2: logging.DEBUG}.get(min(2, verbosity), DEFAULT_LOGGING_LEVEL)\n )\n logger.handlers = []\n handler = logging.StreamHandler(stream)\n handler.setLevel(logging.DEBUG)\n handler.setFormatter(logging.Formatter(LOG_FORMAT))\n logger.addHandler(handler)\n return logger"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef from_config(cls, config, prefix=\"postmark_\", is_uppercase=False):\n kwargs = {}\n for arg in get_args(cls):\n key = prefix + arg\n if is_uppercase:\n key = key.upper()\n else:\n key = key.lower()\n if key in config:\n kwargs[arg] = config[key]\n return cls(**kwargs)", "response": "Instantiates a new instance of the class from a dictionary - like object."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef chunks(container, n):\n for i in range(0, len(container), n):\n yield container[i : i + n]", "response": "Split a container into n - sized chunks."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef sizes(count, offset=0, max_chunk=500):\n if count is None:\n chunk = max_chunk\n while True:\n yield chunk, offset\n offset += chunk\n else:\n while count:\n chunk = min(count, max_chunk)\n count = max(0, count - max_chunk)\n yield chunk, offset\n offset += chunk", "response": "Yields count and offset items from the remote data via count & offset pagination."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef raise_for_response(self, responses):\n exception_messages = [self.client.format_exception_message(response) for response in responses]\n if len(exception_messages) == 1:\n message = exception_messages[0]\n else:\n message = \"[%s]\" % \", \".join(exception_messages)\n raise PostmarkerException(message)", "response": "Constructs appropriate exception from list of responses and raises it."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nconvert list to string with comma separated values. For list is no - op.", "response": "def list_to_csv(value):\n \"\"\"\n Converts list to string with comma separated values. For string is no-op.\n \"\"\"\n if isinstance(value, (list, tuple, set)):\n value = \",\".join(value)\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef prepare_attachments(attachment):\n if isinstance(attachment, tuple):\n result = {\"Name\": attachment[0], \"Content\": attachment[1], \"ContentType\": attachment[2]}\n if len(attachment) == 4:\n result[\"ContentID\"] = attachment[3]\n elif isinstance(attachment, MIMEBase):\n payload = attachment.get_payload()\n content_type = attachment.get_content_type()\n # Special case for message/rfc822\n # Even if RFC implies such attachments being not base64-encoded,\n # Postmark requires all attachments to be encoded in this way\n if content_type == \"message/rfc822\" and not isinstance(payload, str):\n payload = b64encode(payload[0].get_payload(decode=True)).decode()\n result = {\n \"Name\": attachment.get_filename() or \"attachment.txt\",\n \"Content\": payload,\n \"ContentType\": content_type,\n }\n content_id = attachment.get(\"Content-ID\")\n if content_id:\n if content_id.startswith(\"<\") and content_id.endswith(\">\"):\n content_id = content_id[1:-1]\n if (attachment.get(\"Content-Disposition\") or \"\").startswith(\"inline\"):\n content_id = \"cid:%s\" % content_id\n result[\"ContentID\"] = content_id\n elif isinstance(attachment, str):\n content_type = guess_content_type(attachment)\n filename = os.path.basename(attachment)\n with open(attachment, \"rb\") as fd:\n data = fd.read()\n result = {\"Name\": filename, \"Content\": b64encode(data).decode(\"utf-8\"), \"ContentType\": content_type}\n else:\n result = attachment\n return result", "response": "Converts incoming attachment into dictionary."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef as_dict(self):\n data = super(BaseEmail, self).as_dict()\n data[\"Headers\"] = [{\"Name\": name, \"Value\": value} for name, value in data[\"Headers\"].items()]\n for field in (\"To\", \"Cc\", \"Bcc\"):\n if field in data:\n data[field] = list_to_csv(data[field])\n data[\"Attachments\"] = [prepare_attachments(attachment) for attachment in data[\"Attachments\"]]\n return data", "response": "Returns a dict representation of the email."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef attach_binary(self, content, filename):\n content_type = guess_content_type(filename)\n payload = {\"Name\": filename, \"Content\": b64encode(content).decode(\"utf-8\"), \"ContentType\": content_type}\n self.attach(payload)", "response": "Attaches given binary data to the current object."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nconstructing an instance of this class from a MIMEText instance.", "response": "def from_mime(cls, message, manager):\n \"\"\"\n Instantiates ``Email`` instance from ``MIMEText`` instance.\n\n :param message: ``email.mime.text.MIMEText`` instance.\n :param manager: :py:class:`EmailManager` instance.\n :return: :py:class:`Email`\n \"\"\"\n text, html, attachments = deconstruct_multipart(message)\n subject = prepare_header(message[\"Subject\"])\n sender = prepare_header(message[\"From\"])\n to = prepare_header(message[\"To\"])\n cc = prepare_header(message[\"Cc\"])\n bcc = prepare_header(message[\"Bcc\"])\n reply_to = prepare_header(message[\"Reply-To\"])\n tag = getattr(message, \"tag\", None)\n return cls(\n manager=manager,\n From=sender,\n To=to,\n TextBody=text,\n HtmlBody=html,\n Subject=subject,\n Cc=cc,\n Bcc=bcc,\n ReplyTo=reply_to,\n Attachments=attachments,\n Tag=tag,\n )"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nconvert all available emails to dictionaries.", "response": "def as_dict(self, **extra):\n \"\"\"\n Converts all available emails to dictionaries.\n\n :return: List of dictionaries.\n \"\"\"\n return [self._construct_email(email, **extra) for email in self.emails]"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _construct_email(self, email, **extra):\n if isinstance(email, dict):\n email = Email(manager=self._manager, **email)\n elif isinstance(email, (MIMEText, MIMEMultipart)):\n email = Email.from_mime(email, self._manager)\n elif not isinstance(email, Email):\n raise ValueError\n email._update(extra)\n return email.as_dict()", "response": "Constructs a dictionary of data from incoming data."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef send(self, **extra):\n emails = self.as_dict(**extra)\n responses = [self._manager._send_batch(*batch) for batch in chunks(emails, self.MAX_SIZE)]\n return sum(responses, [])", "response": "Sends a batch of emails."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nsends an email message to the specified recipients.", "response": "def send(\n self,\n message=None,\n From=None,\n To=None,\n Cc=None,\n Bcc=None,\n Subject=None,\n Tag=None,\n HtmlBody=None,\n TextBody=None,\n Metadata=None,\n ReplyTo=None,\n Headers=None,\n TrackOpens=None,\n TrackLinks=\"None\",\n Attachments=None,\n ):\n \"\"\"\n Sends a single email.\n\n :param message: :py:class:`Email` or ``email.mime.text.MIMEText`` instance.\n :param str From: The sender email address.\n :param To: Recipient's email address.\n Multiple recipients could be specified as a list or string with comma separated values.\n :type To: str or list\n :param Cc: Cc recipient's email address.\n Multiple Cc recipients could be specified as a list or string with comma separated values.\n :type Cc: str or list\n :param Bcc: Bcc recipient's email address.\n Multiple Bcc recipients could be specified as a list or string with comma separated values.\n :type Bcc: str or list\n :param str Subject: Email subject.\n :param str Tag: Email tag.\n :param str HtmlBody: HTML email message.\n :param str TextBody: Plain text email message.\n :param str ReplyTo: Reply To override email address.\n :param dict Headers: Dictionary of custom headers to include.\n :param bool TrackOpens: Activate open tracking for this email.\n :param str TrackLinks: Activate link tracking for links in the HTML or Text bodies of this email.\n :param list Attachments: List of attachments.\n :return: Information about sent email.\n :rtype: `dict`\n \"\"\"\n assert not (message and (From or To)), \"You should specify either message or From and To parameters\"\n assert TrackLinks in (\"None\", \"HtmlAndText\", \"HtmlOnly\", \"TextOnly\")\n if message is None:\n message = self.Email(\n From=From,\n To=To,\n Cc=Cc,\n Bcc=Bcc,\n Subject=Subject,\n Tag=Tag,\n HtmlBody=HtmlBody,\n TextBody=TextBody,\n Metadata=Metadata,\n ReplyTo=ReplyTo,\n Headers=Headers,\n TrackOpens=TrackOpens,\n TrackLinks=TrackLinks,\n Attachments=Attachments,\n )\n elif isinstance(message, (MIMEText, MIMEMultipart)):\n message = Email.from_mime(message, self)\n elif not isinstance(message, Email):\n raise TypeError(\"message should be either Email or MIMEText or MIMEMultipart instance\")\n return message.send()"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nconstructs an email instance for the given related objects.", "response": "def Email(\n self,\n From,\n To,\n Cc=None,\n Bcc=None,\n Subject=None,\n Tag=None,\n HtmlBody=None,\n TextBody=None,\n Metadata=None,\n ReplyTo=None,\n Headers=None,\n TrackOpens=None,\n TrackLinks=\"None\",\n Attachments=None,\n ):\n \"\"\"\n Constructs :py:class:`Email` instance.\n\n :return: :py:class:`Email`\n \"\"\"\n return Email(\n manager=self,\n From=From,\n To=To,\n Cc=Cc,\n Bcc=Bcc,\n Subject=Subject,\n Tag=Tag,\n HtmlBody=HtmlBody,\n TextBody=TextBody,\n Metadata=Metadata,\n ReplyTo=ReplyTo,\n Headers=Headers,\n TrackOpens=TrackOpens,\n TrackLinks=TrackLinks,\n Attachments=Attachments,\n )"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nconstructing an email template instance.", "response": "def EmailTemplate(\n self,\n TemplateId,\n TemplateModel,\n From,\n To,\n TemplateAlias=None,\n Cc=None,\n Bcc=None,\n Subject=None,\n Tag=None,\n ReplyTo=None,\n Headers=None,\n TrackOpens=None,\n TrackLinks=\"None\",\n Attachments=None,\n InlineCss=True,\n ):\n \"\"\"\n Constructs :py:class:`EmailTemplate` instance.\n\n :return: :py:class:`EmailTemplate`\n \"\"\"\n return EmailTemplate(\n manager=self,\n TemplateId=TemplateId,\n TemplateAlias=TemplateAlias,\n TemplateModel=TemplateModel,\n From=From,\n To=To,\n Cc=Cc,\n Bcc=Bcc,\n Subject=Subject,\n Tag=Tag,\n ReplyTo=ReplyTo,\n Headers=Headers,\n TrackOpens=TrackOpens,\n TrackLinks=TrackLinks,\n Attachments=Attachments,\n InlineCss=InlineCss,\n )"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nactivate the bounce instance and updates the latest data.", "response": "def activate(self):\n \"\"\"\n Activates the bounce instance and updates it with the latest data.\n\n :return: Activation status.\n :rtype: `str`\n \"\"\"\n response = self._manager.activate(self.ID)\n self._update(response[\"Bounce\"])\n return response[\"Message\"]"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn a list of all bounces for a given set of attributes.", "response": "def all(\n self,\n count=500,\n offset=0,\n type=None,\n inactive=None,\n emailFilter=None,\n tag=None,\n messageID=None,\n fromdate=None,\n todate=None,\n ):\n \"\"\"\n Returns many bounces.\n\n :param int count: Number of bounces to return per request.\n :param int offset: Number of bounces to skip.\n :param str type: Filter by type of bounce.\n :param bool inactive: Filter by emails that were deactivated by Postmark due to the bounce.\n :param str emailFilter: Filter by email address.\n :param str tag: Filter by tag.\n :param str messageID: Filter by messageID.\n :param date fromdate: Filter messages starting from the date specified (inclusive).\n :param date todate: Filter messages up to the date specified (inclusive).\n :return: A list of :py:class:`Bounce` instances.\n :rtype: `list`\n \"\"\"\n responses = self.call_many(\n \"GET\",\n \"/bounces/\",\n count=count,\n offset=offset,\n type=type,\n inactive=inactive,\n emailFilter=emailFilter,\n tag=tag,\n messageID=messageID,\n fromdate=fromdate,\n todate=todate,\n )\n return self.expand_responses(responses, \"Bounces\")"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef update_kwargs(self, kwargs, count, offset):\n kwargs.update({self.count_key: count, self.offset_key: offset})\n return kwargs", "response": "Helper to support handy dictionaries merging on all Python versions."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef overview(self, tag=None, fromdate=None, todate=None):\n return self.call(\"GET\", \"/stats/outbound\", tag=tag, fromdate=fromdate, todate=todate)", "response": "Gets a brief overview of all of your outbound email."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nget a total count of emails you ve sent out.", "response": "def sends(self, tag=None, fromdate=None, todate=None):\n \"\"\"\n Gets a total count of emails you\u2019ve sent out.\n \"\"\"\n return self.call(\"GET\", \"/stats/outbound/sends\", tag=tag, fromdate=fromdate, todate=todate)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef bounces(self, tag=None, fromdate=None, todate=None):\n return self.call(\"GET\", \"/stats/outbound/bounces\", tag=tag, fromdate=fromdate, todate=todate)", "response": "Gets the total number of emails that have been sent out that have been bounced."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngetting the total number of recipients who have marked your email as spam.", "response": "def spam(self, tag=None, fromdate=None, todate=None):\n \"\"\"\n Gets a total count of recipients who have marked your email as spam.\n \"\"\"\n return self.call(\"GET\", \"/stats/outbound/spam\", tag=tag, fromdate=fromdate, todate=todate)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef tracked(self, tag=None, fromdate=None, todate=None):\n return self.call(\"GET\", \"/stats/outbound/tracked\", tag=tag, fromdate=fromdate, todate=todate)", "response": "Gets a total count of emails you have sent with open tracking or link tracking enabled."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngetting the total number of recipients who opened your emails.", "response": "def opens(self, tag=None, fromdate=None, todate=None):\n \"\"\"\n Gets total counts of recipients who opened your emails.\n This is only recorded when open tracking is enabled for that email.\n \"\"\"\n return self.call(\"GET\", \"/stats/outbound/opens\", tag=tag, fromdate=fromdate, todate=todate)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngets an overview of the platforms used to open your emails.", "response": "def opens_platforms(self, tag=None, fromdate=None, todate=None):\n \"\"\"\n Gets an overview of the platforms used to open your emails.\n This is only recorded when open tracking is enabled for that email.\n \"\"\"\n return self.call(\"GET\", \"/stats/outbound/opens/platforms\", tag=tag, fromdate=fromdate, todate=todate)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef emailclients(self, tag=None, fromdate=None, todate=None):\n return self.call(\"GET\", \"/stats/outbound/opens/emailclients\", tag=tag, fromdate=fromdate, todate=todate)", "response": "Gets an overview of the email clients used to open your emails."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngets the total number of times that a given email was read.", "response": "def readtimes(self, tag=None, fromdate=None, todate=None):\n \"\"\"\n Gets the length of time that recipients read emails along with counts for each time.\n This is only recorded when open tracking is enabled for that email.\n Read time tracking stops at 20 seconds, so any read times above that will appear in the 20s+ field.\n \"\"\"\n return self.call(\"GET\", \"/stats/outbound/opens/readtimes\", tag=tag, fromdate=fromdate, todate=todate)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nget the total number of unique links that were clicked.", "response": "def clicks(self, tag=None, fromdate=None, todate=None):\n \"\"\"\n Gets total counts of unique links that were clicked.\n \"\"\"\n return self.call(\"GET\", \"/stats/outbound/clicks\", tag=tag, fromdate=fromdate, todate=todate)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngetting an overview of the browser families used to open links in your emails.", "response": "def browserfamilies(self, tag=None, fromdate=None, todate=None):\n \"\"\"\n Gets an overview of the browsers used to open links in your emails.\n This is only recorded when Link Tracking is enabled for that email.\n \"\"\"\n return self.call(\"GET\", \"/stats/outbound/clicks/browserfamilies\", tag=tag, fromdate=fromdate, todate=todate)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngetting an overview of the browser platforms used to open your emails.", "response": "def clicks_platforms(self, tag=None, fromdate=None, todate=None):\n \"\"\"\n Gets an overview of the browser platforms used to open your emails.\n This is only recorded when Link Tracking is enabled for that email.\n \"\"\"\n return self.call(\"GET\", \"/stats/outbound/clicks/platforms\", tag=tag, fromdate=fromdate, todate=todate)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets an overview of which part of the email links were clicked from.", "response": "def location(self, tag=None, fromdate=None, todate=None):\n \"\"\"\n Gets an overview of which part of the email links were clicked from (HTML or Text).\n This is only recorded when Link Tracking is enabled for that email.\n \"\"\"\n return self.call(\"GET\", \"/stats/outbound/clicks/location\", tag=tag, fromdate=fromdate, todate=todate)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef line_rate(self, filename=None):\n if filename is None:\n el = self.xml\n else:\n el = self._get_class_element_by_filename(filename)\n\n return float(el.attrib['line-rate'])", "response": "Returns the global line rate of the coverage report."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the global branch rate of the coverage report.", "response": "def branch_rate(self, filename=None):\n \"\"\"\n Return the global branch rate of the coverage report. If the\n `filename` file is given, return the branch rate of the file.\n \"\"\"\n if filename is None:\n el = self.xml\n else:\n el = self._get_class_element_by_filename(filename)\n\n return float(el.attrib['branch-rate'])"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn a list of uncovered line numbers for each of the missed statements for the file filename.", "response": "def missed_statements(self, filename):\n \"\"\"\n Return a list of uncovered line numbers for each of the missed\n statements found for the file `filename`.\n \"\"\"\n el = self._get_class_element_by_filename(filename)\n lines = el.xpath('./lines/line[@hits=0]')\n return [int(l.attrib['number']) for l in lines]"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef line_statuses(self, filename):\n line_elements = self._get_lines_by_filename(filename)\n\n lines_w_status = []\n for line in line_elements:\n lineno = int(line.attrib['number'])\n status = line.attrib['hits'] != '0'\n lines_w_status.append((lineno, status))\n\n return lines_w_status", "response": "Return a list of tuples that each element is a line number and a status of the line which can be coverageed."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns a list of extrapolated uncovered line numbers for the given file filename.", "response": "def missed_lines(self, filename):\n \"\"\"\n Return a list of extrapolated uncovered line numbers for the\n file `filename` according to `Cobertura.line_statuses`.\n \"\"\"\n statuses = self.line_statuses(filename)\n statuses = extrapolate_coverage(statuses)\n return [lno for lno, status in statuses if status is False]"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef file_source(self, filename):\n lines = []\n try:\n with self.filesystem.open(filename) as f:\n line_statuses = dict(self.line_statuses(filename))\n for lineno, source in enumerate(f, start=1):\n line_status = line_statuses.get(lineno)\n line = Line(lineno, source, line_status, None)\n lines.append(line)\n\n except self.filesystem.FileNotFound as file_not_found:\n lines.append(\n Line(0, '%s not found' % file_not_found.path, None, None)\n )\n\n return lines", "response": "Return a list of namedtuple Line for each line of code found in the\n source file with the given filename."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef total_misses(self, filename=None):\n if filename is not None:\n return len(self.missed_statements(filename))\n\n total = 0\n for filename in self.files():\n total += len(self.missed_statements(filename))\n\n return total", "response": "Return the total number of uncovered statements for the file\n filename."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef total_hits(self, filename=None):\n if filename is not None:\n return len(self.hit_statements(filename))\n\n total = 0\n for filename in self.files():\n total += len(self.hit_statements(filename))\n\n return total", "response": "Return the total number of covered statements for the file\n filename."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef total_statements(self, filename=None):\n if filename is not None:\n statements = self._get_lines_by_filename(filename)\n return len(statements)\n\n total = 0\n for filename in self.files():\n statements = self._get_lines_by_filename(filename)\n total += len(statements)\n\n return total", "response": "Return the total number of statements for the file\n filename."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef files(self):\n # maybe replace with a trie at some point? see has_file FIXME\n already_seen = set()\n filenames = []\n\n for el in self.xml.xpath(\"//class\"):\n filename = el.attrib['filename']\n if filename in already_seen:\n continue\n already_seen.add(filename)\n filenames.append(filename)\n\n return filenames", "response": "Return the list of available files in the coverage report."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a list of source lines of file filename.", "response": "def source_lines(self, filename):\n \"\"\"\n Return a list for source lines of file `filename`.\n \"\"\"\n with self.filesystem.open(filename) as f:\n return f.readlines()"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef has_better_coverage(self):\n for filename in self.files():\n if self.diff_total_misses(filename) > 0:\n return False\n return True", "response": "Return True if coverage of has improved False otherwise."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn True if all changes have been covered False otherwise.", "response": "def has_all_changes_covered(self):\n \"\"\"\n Return `True` if all changes have been covered, `False` otherwise.\n \"\"\"\n for filename in self.files():\n for hunk in self.file_source_hunks(filename):\n for line in hunk:\n if line.reason is None:\n continue # line untouched\n if line.status is False:\n return False # line not covered\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _diff_attr(self, attr_name, filename):\n if filename is not None:\n files = [filename]\n else:\n files = self.files()\n\n total_count = 0.0\n for filename in files:\n if self.cobertura1.has_file(filename):\n method = getattr(self.cobertura1, attr_name)\n count1 = method(filename)\n else:\n count1 = 0.0\n method = getattr(self.cobertura2, attr_name)\n count2 = method(filename)\n total_count += count2 - count1\n\n return total_count", "response": "Return the difference between the attributes of the related object and the file filename."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a list of 2 - element tuples where the lineno is a missed line number and is_new is True if the missed line was introduced or removed.", "response": "def diff_missed_lines(self, filename):\n \"\"\"\n Return a list of 2-element tuples `(lineno, is_new)` for the given\n file `filename` where `lineno` is a missed line number and `is_new`\n indicates whether the missed line was introduced (True) or removed\n (False).\n \"\"\"\n line_changed = []\n for line in self.file_source(filename):\n if line.status is not None:\n is_new = not line.status\n line_changed.append((line.number, is_new))\n return line_changed"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning a list of namedtuple Line for each line of code found in the file filename.", "response": "def file_source(self, filename):\n \"\"\"\n Return a list of namedtuple `Line` for each line of code found in the\n given file `filename`.\n\n \"\"\"\n if self.cobertura1.has_file(filename) and \\\n self.cobertura1.filesystem.has_file(filename):\n lines1 = self.cobertura1.source_lines(filename)\n line_statuses1 = dict(self.cobertura1.line_statuses(\n filename))\n else:\n lines1 = []\n line_statuses1 = {}\n\n lines2 = self.cobertura2.source_lines(filename)\n line_statuses2 = dict(self.cobertura2.line_statuses(filename))\n\n # Build a dict of lineno2 -> lineno1\n lineno_map = reconcile_lines(lines2, lines1)\n\n lines = []\n for lineno, source in enumerate(lines2, start=1):\n status = None\n reason = None\n if lineno not in lineno_map:\n # line was added or removed, just use whatever coverage status\n # is available as there is nothing to compare against.\n status = line_statuses2.get(lineno)\n reason = 'line-edit'\n else:\n other_lineno = lineno_map[lineno]\n line_status1 = line_statuses1.get(other_lineno)\n line_status2 = line_statuses2.get(lineno)\n if line_status1 is line_status2:\n status = None # unchanged\n reason = None\n elif line_status1 is True and line_status2 is False:\n status = False # decreased\n reason = 'cov-down'\n elif line_status1 is False and line_status2 is True:\n status = True # increased\n reason = 'cov-up'\n\n line = Line(lineno, source, status, reason)\n lines.append(line)\n\n return lines"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef file_source_hunks(self, filename):\n lines = self.file_source(filename)\n hunks = hunkify_lines(lines)\n return hunks", "response": "Like file_source but returns a list of line hunks that have changed for the given file filename."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nflushes the queue periodically.", "response": "def monitor(self):\n \"\"\"Flushes the queue periodically.\"\"\"\n while self.monitor_running.is_set():\n if time.time() - self.last_flush > self.batch_time:\n if not self.queue.empty():\n logger.info(\"Queue Flush: time without flush exceeded\")\n self.flush_queue()\n time.sleep(self.batch_time)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef put_records(self, records, partition_key=None):\n for record in records:\n self.put_record(record, partition_key)", "response": "Adds a list of data records to the record queue in the proper format."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nadding data to the record queue in the proper format.", "response": "def put_record(self, data, partition_key=None):\n \"\"\"Add data to the record queue in the proper format.\n\n Parameters\n ----------\n data : str\n Data to send.\n partition_key: str\n Hash that determines which shard a given data record belongs to.\n\n \"\"\"\n # Byte encode the data\n data = encode_data(data)\n\n # Create a random partition key if not provided\n if not partition_key:\n partition_key = uuid.uuid4().hex\n\n # Build the record\n record = {\n 'Data': data,\n 'PartitionKey': partition_key\n }\n\n # Flush the queue if it reaches the batch size\n if self.queue.qsize() >= self.batch_size:\n logger.info(\"Queue Flush: batch size reached\")\n self.pool.submit(self.flush_queue)\n\n # Append the record\n logger.debug('Putting record \"{}\"'.format(record['Data'][:100]))\n self.queue.put(record)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nflushes the queue and waits for the executor to finish.", "response": "def close(self):\n \"\"\"Flushes the queue and waits for the executor to finish.\"\"\"\n logger.info('Closing producer')\n self.flush_queue()\n self.monitor_running.clear()\n self.pool.shutdown()\n logger.info('Producer closed')"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef flush_queue(self):\n records = []\n\n while not self.queue.empty() and len(records) < self.batch_size:\n records.append(self.queue.get())\n\n if records:\n self.send_records(records)\n self.last_flush = time.time()", "response": "Grab all the current records in the queue and send them."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef send_records(self, records, attempt=0):\n\n # If we already tried more times than we wanted, save to a file\n if attempt > self.max_retries:\n logger.warning('Writing {} records to file'.format(len(records)))\n with open('failed_records.dlq', 'ab') as f:\n for r in records:\n f.write(r.get('Data'))\n return\n\n # Sleep before retrying\n if attempt:\n time.sleep(2 ** attempt * .1)\n\n response = self.kinesis_client.put_records(StreamName=self.stream_name,\n Records=records)\n failed_record_count = response['FailedRecordCount']\n\n # Grab failed records\n if failed_record_count:\n logger.warning('Retrying failed records')\n failed_records = []\n for i, record in enumerate(response['Records']):\n if record.get('ErrorCode'):\n failed_records.append(records[i])\n\n # Recursive call\n attempt += 1\n self.send_records(failed_records, attempt=attempt)", "response": "Send records to the Kinesis stream."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nassuming the list is sorted.", "response": "def rangify(number_list):\n \"\"\"Assumes the list is sorted.\"\"\"\n if not number_list:\n return number_list\n\n ranges = []\n\n range_start = prev_num = number_list[0]\n for num in number_list[1:]:\n if num != (prev_num + 1):\n ranges.append((range_start, prev_num))\n range_start = num\n prev_num = num\n\n ranges.append((range_start, prev_num))\n return ranges"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngiving the following input return the expanded lines with their extrapolated line status.", "response": "def extrapolate_coverage(lines_w_status):\n \"\"\"\n Given the following input:\n\n >>> lines_w_status = [\n (1, True),\n (4, True),\n (7, False),\n (9, False),\n ]\n\n Return expanded lines with their extrapolated line status.\n\n >>> extrapolate_coverage(lines_w_status) == [\n (1, True),\n (2, True),\n (3, True),\n (4, True),\n (5, None),\n (6, None),\n (7, False),\n (8, False),\n (9, False),\n ]\n\n \"\"\"\n lines = []\n\n prev_lineno = 0\n prev_status = True\n for lineno, status in lines_w_status:\n while (lineno - prev_lineno) > 1:\n prev_lineno += 1\n if prev_status is status:\n lines.append((prev_lineno, status))\n else:\n lines.append((prev_lineno, None))\n lines.append((lineno, status))\n prev_lineno = lineno\n prev_status = status\n\n return lines"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a dict that maps line numbers lineno1 to line numbers lineno2.", "response": "def reconcile_lines(lines1, lines2):\n \"\"\"\n Return a dict `{lineno1: lineno2}` which reconciles line numbers `lineno1`\n of list `lines1` to line numbers `lineno2` of list `lines2`. Only lines\n that are common in both sets are present in the dict, lines unique to one\n of the sets are omitted.\n \"\"\"\n differ = difflib.Differ()\n diff = differ.compare(lines1, lines2)\n\n SAME = ' '\n ADDED = '+ '\n REMOVED = '- '\n INFO = '? '\n\n lineno_map = {} # {lineno1: lineno2, ...}\n lineno1_offset = 0\n lineno2 = 1\n\n for diffline in diff:\n if diffline.startswith(INFO):\n continue\n\n if diffline.startswith(SAME):\n lineno1 = lineno2 + lineno1_offset\n lineno_map[lineno1] = lineno2\n\n elif diffline.startswith(ADDED):\n lineno1_offset -= 1\n\n elif diffline.startswith(REMOVED):\n lineno1_offset += 1\n continue\n\n lineno2 += 1\n\n return lineno_map"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef hunkify_lines(lines, context=3):\n # Find contiguous line changes\n ranges = []\n range_start = None\n for i, line in enumerate(lines):\n if line.status is not None:\n if range_start is None:\n range_start = i\n continue\n elif range_start is not None:\n range_stop = i\n ranges.append((range_start, range_stop))\n range_start = None\n else:\n # Append the last range\n if range_start is not None:\n range_stop = i\n ranges.append((range_start, range_stop))\n\n # add context\n ranges_w_context = []\n for range_start, range_stop in ranges:\n range_start = range_start - context\n range_start = range_start if range_start >= 0 else 0\n range_stop = range_stop + context\n ranges_w_context.append((range_start, range_stop))\n\n # merge overlapping hunks\n merged_ranges = ranges_w_context[:1]\n for range_start, range_stop in ranges_w_context[1:]:\n prev_start, prev_stop = merged_ranges[-1]\n if range_start <= prev_stop:\n range_start = prev_start\n merged_ranges[-1] = (range_start, range_stop)\n else:\n merged_ranges.append((range_start, range_stop))\n\n # build final hunks\n hunks = []\n for range_start, range_stop in merged_ranges:\n hunk = lines[range_start:range_stop]\n hunks.append(hunk)\n\n return hunks", "response": "Return a list of line hunks given a list of lines."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef show(cobertura_file, format, output, source, source_prefix):\n cobertura = Cobertura(cobertura_file, source=source)\n Reporter = reporters[format]\n reporter = Reporter(cobertura)\n report = reporter.generate()\n\n if not isinstance(report, bytes):\n report = report.encode('utf-8')\n\n isatty = True if output is None else output.isatty()\n click.echo(report, file=output, nl=isatty)", "response": "show coverage summary of a Cobertura report"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncompares coverage of two Cobertura reports", "response": "def diff(\n cobertura_file1, cobertura_file2,\n color, format, output, source1, source2,\n source_prefix1, source_prefix2, source):\n \"\"\"compare coverage of two Cobertura reports\"\"\"\n cobertura1 = Cobertura(\n cobertura_file1,\n source=source1,\n source_prefix=source_prefix1\n )\n cobertura2 = Cobertura(\n cobertura_file2,\n source=source2,\n source_prefix=source_prefix2\n )\n\n Reporter = delta_reporters[format]\n reporter_args = [cobertura1, cobertura2]\n reporter_kwargs = {'show_source': source}\n\n isatty = True if output is None else output.isatty()\n\n if format == 'text':\n color = isatty if color is None else color is True\n reporter_kwargs['color'] = color\n\n reporter = Reporter(*reporter_args, **reporter_kwargs)\n report = reporter.generate()\n\n if not isinstance(report, bytes):\n report = report.encode('utf-8')\n\n click.echo(report, file=output, nl=isatty, color=color)\n\n exit_code = get_exit_code(reporter.differ, source)\n raise SystemExit(exit_code)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef open(self, filename):\n filename = self.real_filename(filename)\n\n if not os.path.exists(filename):\n raise self.FileNotFound(filename)\n\n with codecs.open(filename, encoding='utf-8') as f:\n yield f", "response": "Yield a file - like object for filename."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ninject a message into a topic.", "response": "def topic_inject(self, topic_name, _msg_content=None, **kwargs):\n \"\"\"\n Injecting message into topic. if _msg_content, we inject it directly. if not, we use all extra kwargs\n :param topic_name: name of the topic\n :param _msg_content: optional message content\n :param kwargs: each extra kwarg will be put int he message is structure matches\n :return:\n \"\"\"\n #changing unicode to string ( testing stability of multiprocess debugging )\n if isinstance(topic_name, unicode):\n topic_name = unicodedata.normalize('NFKD', topic_name).encode('ascii', 'ignore')\n\n if _msg_content is not None:\n # logging.warn(\"injecting {msg} into {topic}\".format(msg=_msg_content, topic=topic_name))\n res = self.topic_svc.call(args=(topic_name, _msg_content,))\n else: # default kwargs is {}\n # logging.warn(\"injecting {msg} into {topic}\".format(msg=kwargs, topic=topic_name))\n res = self.topic_svc.call(args=(topic_name, kwargs,))\n\n return res is None"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nsets the value of a parameter in a topic.", "response": "def param_set(self, param_name, _value=None, **kwargs):\n \"\"\"\n Setting parameter. if _value, we inject it directly. if not, we use all extra kwargs\n :param topic_name: name of the topic\n :param _value: optional value\n :param kwargs: each extra kwarg will be put in the value if structure matches\n :return:\n \"\"\"\n #changing unicode to string ( testing stability of multiprocess debugging )\n if isinstance(param_name, unicode):\n param_name = unicodedata.normalize('NFKD', param_name).encode('ascii', 'ignore')\n\n _value = _value or {}\n\n if kwargs:\n res = self.param_svc.call(args=(param_name, kwargs,))\n elif _value is not None:\n res = self.param_svc.call(args=(param_name, _value,))\n else: # if _msg_content is None the request is invalid.\n # just return something to mean False.\n res = 'WRONG SET'\n\n return res is None"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef run(interface, config, logfile, ros_args):\n logging.info(\n 'pyros started with : interface {interface} config {config} logfile {logfile} ros_args {ros_args}'.format(\n interface=interface, config=config, logfile=logfile, ros_args=ros_args))\n\n if interface == 'ros':\n node_proc = pyros_rosinterface_launch(node_name='pyros_rosinterface', pyros_config=config, ros_argv=ros_args)\n else:\n node_proc = None # NOT IMPLEMENTED\n\n # node_proc.daemon = True # we do NOT want a daemon(would stop when this main process exits...)\n client_conn = node_proc.start()", "response": "Start a pyros node."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nstoring nick user host in kwargs", "response": "def nickmask(prefix: str, kwargs: Dict[str, Any]) -> None:\n \"\"\" store nick, user, host in kwargs if prefix is correct format \"\"\"\n if \"!\" in prefix and \"@\" in prefix:\n # From a user\n kwargs[\"nick\"], remainder = prefix.split(\"!\", 1)\n kwargs[\"user\"], kwargs[\"host\"] = remainder.split(\"@\", 1)\n else:\n # From a server, probably the host\n kwargs[\"host\"] = prefix"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef split_line(msg: str) -> Tuple[str, str, List[str]]:\n match = RE_IRCLINE.match(msg)\n if not match:\n raise ValueError(\"Invalid line\")\n\n prefix = match.group(\"prefix\") or \"\"\n command = match.group(\"command\")\n params = (match.group(\"params\") or \"\").split()\n message = match.group(\"message\") or \"\"\n\n if message:\n params.append(message)\n\n return prefix, command, params", "response": "Parse a line of text according to RFC 2812 for routing"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef b(field: str, kwargs: Dict[str, Any],\n present: Optional[Any] = None, missing: Any = '') -> str:\n \"\"\"\n Return `present` value (default to `field`) if `field` in `kwargs` and\n Truthy, otherwise return `missing` value\n \"\"\"\n if kwargs.get(field):\n return field if present is None else str(present)\n return str(missing)", "response": "Return the value of a field in the order they appear in the order they appear in."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\naliases for more readable command construction", "response": "def f(field: str, kwargs: Dict[str, Any],\n default: Optional[Any] = None) -> str:\n \"\"\" Alias for more readable command construction \"\"\"\n if default is not None:\n return str(kwargs.get(field, default))\n return str(kwargs[field])"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef pack(field: str, kwargs: Dict[str, Any],\n default: Optional[Any] = None, sep: str=',') -> str:\n \"\"\" Util for joining multiple fields with commas \"\"\"\n if default is not None:\n value = kwargs.get(field, default)\n else:\n value = kwargs[field]\n if isinstance(value, str):\n return value\n elif isinstance(value, collections.abc.Iterable):\n return sep.join(str(f) for f in value)\n else:\n return str(value)", "response": "Util for joining multiple fields with commas"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\npack a command to send to an IRC server", "response": "def pack_command(command: str, **kwargs: Any) -> str:\n \"\"\" Pack a command to send to an IRC server \"\"\"\n if not command:\n raise ValueError(\"Must provide a command\")\n if not isinstance(command, str):\n raise ValueError(\"Command must be a string\")\n command = command.upper()\n\n # ========================================================================\n # For each command, provide:\n # 1. a link to the definition in rfc2812\n # 2. the normalized grammar, which may not equate to the rfc grammar\n # the normalized grammar will use the keys expected in kwargs,\n # which usually do NOT line up with rfc2812. They may also make\n # optional fields which are required in rfc2812, by providing\n # the most common or reasonable defaults.\n # 3. exhaustive examples, preferring normalized form of\n # the rfc2812 examples\n # ========================================================================\n\n # ========================================================================\n # Normalized grammar:\n # : should not be provided; it denotes the beginning of the last\n # field, which may contain spaces\n # [] indicates an optional field\n # <> denote the key that the field will be filled with\n # because fields are filled from a dict, required fields may follow\n # optional fields - see USER command, where mode is optional\n # (and defaults to 0)\n # \"\" indicates a literal value that is inserted if present\n # ========================================================================\n\n # PASS\n # https://tools.ietf.org/html/rfc2812#section-3.1.1\n # PASS
')\r\n body_html = re.match(pat, str(spans[1]).replace(\r\n '\\n', '')).groups()[0]\r\n\r\n else:\r\n # comment deleted\r\n user = ''\r\n time_ago = ''\r\n comment_id = -1\r\n body = '[deleted]'\r\n body_html = '[deleted]'\r\n\r\n comment = Comment(comment_id, level, user, time_ago,\r\n body, body_html)\r\n comments.append(comment)\r\n\r\n # Move on to the next page of comments, or exit the loop if there\r\n # is no next page.\r\n next_page_url = self._get_next_page(soup, current_page)\r\n if not next_page_url:\r\n break\r\n\r\n soup = get_soup(page=next_page_url)\r\n current_page += 1\r\n\r\n previous_comment = None\r\n # for comment in comments:\r\n # if comment.level == 0:\r\n # previous_comment = comment\r\n # else:\r\n # level_difference = comment.level - previous_comment.level\r\n # previous_comment.body_html += '\\n' + '\\t' * level_difference \\\r\n # + comment.body_html\r\n # previous_comment.body += '\\n' + '\\t' * level_difference + \\\r\n # comment.body\r\n return comments"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn an instance of the class instance from the ID of the item.", "response": "def fromid(self, item_id):\r\n \"\"\"\r\n Initializes an instance of Story for given item_id.\r\n It is assumed that the story referenced by item_id is valid\r\n and does not raise any HTTP errors.\r\n item_id is an int.\r\n \"\"\"\r\n if not item_id:\r\n raise Exception('Need an item_id for a story')\r\n # get details about a particular story\r\n soup = get_item_soup(item_id)\r\n\r\n # this post has not been scraped, so we explititly get all info\r\n story_id = item_id\r\n rank = -1\r\n\r\n # to extract meta information about the post\r\n info_table = soup.findChildren('table')[2]\r\n # [0] = title, domain, [1] = points, user, time, comments\r\n info_rows = info_table.findChildren('tr')\r\n\r\n # title, domain\r\n title_row = info_rows[0].findChildren('td')[1]\r\n title = title_row.find('a').text\r\n try:\r\n domain = title_row.find('span').string[2:-2]\r\n # domain found\r\n is_self = False\r\n link = title_row.find('a').get('href')\r\n except AttributeError:\r\n # self post\r\n domain = BASE_URL\r\n is_self = True\r\n link = '%s/item?id=%s' % (BASE_URL, item_id)\r\n\r\n # points, user, time, comments\r\n meta_row = info_rows[1].findChildren('td')[1].contents\r\n # [789 points, u' by ', endianswap,\r\n # u' 8 hours ago | ', 238 comments]\r\n\r\n points = int(re.match(r'^(\\d+)\\spoint.*', meta_row[0].text).groups()[0])\r\n submitter = meta_row[2].text\r\n submitter_profile = '%s/%s' % (BASE_URL, meta_row[2].get('href'))\r\n published_time = ' '.join(meta_row[3].strip().split()[:3])\r\n comments_link = '%s/item?id=%s' % (BASE_URL, item_id)\r\n try:\r\n num_comments = int(re.match(r'(\\d+)\\s.*', meta_row[\r\n 4].text).groups()[0])\r\n except AttributeError:\r\n num_comments = 0\r\n story = Story(rank, story_id, title, link, domain, points, submitter,\r\n published_time, submitter_profile, num_comments,\r\n comments_link, is_self)\r\n return story"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ncompares a list of names from a name component based on settings", "response": "def compare_name_component(list1, list2, settings, use_ratio=False):\n \"\"\"\n Compare a list of names from a name component based on settings\n \"\"\"\n if not list1[0] or not list2[0]:\n not_required = not settings['required']\n return not_required * 100 if use_ratio else not_required\n\n if len(list1) != len(list2):\n return False\n\n compare_func = _ratio_compare if use_ratio else _normal_compare\n return compare_func(list1, list2, settings)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef equate_initial(name1, name2):\n if len(name1) == 0 or len(name2) == 0:\n return False\n\n if len(name1) == 1 or len(name2) == 1:\n return name1[0] == name2[0]\n\n return name1 == name2", "response": "Evaluates whether two names are the initial of the other."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef equate_prefix(name1, name2):\n\n if len(name1) == 0 or len(name2) == 0:\n return False\n\n return name1.startswith(name2) or name2.startswith(name1)", "response": "Evaluate whether two names are the same prefix."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef equate_nickname(name1, name2):\n # Convert '-ie' and '-y' to the root name\n nickname_regex = r'(.)\\1(y|ie)$'\n root_regex = r'\\1'\n\n name1 = re.sub(nickname_regex, root_regex, name1)\n name2 = re.sub(nickname_regex, root_regex, name2)\n\n if equate_prefix(name1, name2):\n return True\n\n return False", "response": "Evaluates whether two names are the same based on common nickname patterns."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nconverts unicode - specific characters to their equivalent ascii", "response": "def make_ascii(word):\n \"\"\"\n Converts unicode-specific characters to their equivalent ascii\n \"\"\"\n if sys.version_info < (3, 0, 0):\n word = unicode(word)\n else:\n word = str(word)\n\n normalized = unicodedata.normalize('NFKD', word)\n\n return normalized.encode('ascii', 'ignore').decode('utf-8')"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef seq_ratio(word1, word2):\n raw_ratio = SequenceMatcher(None, word1, word2).ratio()\n return int(round(100 * raw_ratio))", "response": "Returns the ratio of a sequence match for two words\n Returns 0 if no match is found"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef deep_update_dict(default, options):\n for key in options.keys():\n default_setting = default.get(key)\n new_setting = options.get(key)\n if isinstance(default_setting, dict):\n deep_update_dict(default_setting, new_setting)\n else:\n default[key] = new_setting", "response": "Updates the values in a nested dict while unspecified values will remain unchanged"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nget base output path for a list of songs for download.", "response": "def template_to_base_path(template, google_songs):\n\t\"\"\"Get base output path for a list of songs for download.\"\"\"\n\n\tif template == os.getcwd() or template == '%suggested%':\n\t\tbase_path = os.getcwd()\n\telse:\n\t\ttemplate = os.path.abspath(template)\n\t\tsong_paths = [template_to_filepath(template, song) for song in google_songs]\n\t\tbase_path = os.path.dirname(os.path.commonprefix(song_paths))\n\n\treturn base_path"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ncreating a randomly generated bit string of the given length with the probability of bit_prob equal to bit_prob.", "response": "def random(cls, length, bit_prob=.5):\n \"\"\"Create a bit string of the given length, with the probability of\n each bit being set equal to bit_prob, which defaults to .5.\n\n Usage:\n # Create a random BitString of length 10 with mostly zeros.\n bits = BitString.random(10, bit_prob=.1)\n\n Arguments:\n length: An int, indicating the desired length of the result.\n bit_prob: A float in the range [0, 1]. This is the probability\n of any given bit in the result having a value of 1; default\n is .5, giving 0 and 1 equal probabilities of appearance for\n each bit's value.\n Return:\n A randomly generated BitString instance of the requested\n length.\n \"\"\"\n\n assert isinstance(length, int) and length >= 0\n assert isinstance(bit_prob, (int, float)) and 0 <= bit_prob <= 1\n\n bits = 0\n for _ in range(length):\n bits <<= 1\n bits += (random.random() < bit_prob)\n\n return cls(bits, length)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncreates a new bitstring containing the given number of points and a new length.", "response": "def crossover_template(cls, length, points=2):\n \"\"\"Create a crossover template with the given number of points. The\n crossover template can be used as a mask to crossover two\n bitstrings of the same length.\n\n Usage:\n assert len(parent1) == len(parent2)\n template = BitString.crossover_template(len(parent1))\n inv_template = ~template\n child1 = (parent1 & template) | (parent2 & inv_template)\n child2 = (parent1 & inv_template) | (parent2 & template)\n\n Arguments:\n length: An int, indicating the desired length of the result.\n points: An int, the number of crossover points.\n Return:\n A BitString instance of the requested length which can be used\n as a crossover template.\n \"\"\"\n\n assert isinstance(length, int) and length >= 0\n assert isinstance(points, int) and points >= 0\n\n # Select the crossover points.\n points = random.sample(range(length + 1), points)\n\n # Prep the points for the loop.\n points.sort()\n points.append(length)\n\n # Fill the bits in with alternating ranges of 0 and 1 according to\n # the selected crossover points.\n previous = 0\n include_range = bool(random.randrange(2))\n bits = 0\n for point in points:\n if point > previous:\n bits <<= point - previous\n if include_range:\n bits += (1 << (point - previous)) - 1\n include_range = not include_range\n previous = point\n\n return cls(bits, length)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef count(self):\n result = 0\n bits = self._bits\n while bits:\n result += bits % 2\n bits >>= 1\n return result", "response": "Returns the number of bits set to True in the bit string."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nwait for an event on any channel.", "response": "def drain_events(self, allowed_methods=None, timeout=None):\n \"\"\"Wait for an event on any channel.\"\"\"\n return self.wait_multi(self.channels.values(), timeout=timeout)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nwait for an event on a channel.", "response": "def wait_multi(self, channels, allowed_methods=None, timeout=None):\n \"\"\"Wait for an event on a channel.\"\"\"\n chanmap = dict((chan.channel_id, chan) for chan in channels)\n chanid, method_sig, args, content = self._wait_multiple(\n chanmap.keys(), allowed_methods, timeout=timeout)\n\n channel = chanmap[chanid]\n\n if content \\\n and channel.auto_decode \\\n and hasattr(content, 'content_encoding'):\n try:\n content.body = content.body.decode(content.content_encoding)\n except Exception:\n pass\n\n amqp_method = channel._METHOD_MAP.get(method_sig, None)\n\n if amqp_method is None:\n raise Exception('Unknown AMQP method (%d, %d)' % method_sig)\n\n if content is None:\n return amqp_method(channel, args)\n else:\n return amqp_method(channel, args, content)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nestablishing connection to the AMQP broker.", "response": "def establish_connection(self):\n \"\"\"Establish connection to the AMQP broker.\"\"\"\n conninfo = self.connection\n if not conninfo.hostname:\n raise KeyError(\"Missing hostname for AMQP connection.\")\n if conninfo.userid is None:\n raise KeyError(\"Missing user id for AMQP connection.\")\n if conninfo.password is None:\n raise KeyError(\"Missing password for AMQP connection.\")\n if not conninfo.port:\n conninfo.port = self.default_port\n return Connection(host=conninfo.host,\n userid=conninfo.userid,\n password=conninfo.password,\n virtual_host=conninfo.virtual_host,\n insist=conninfo.insist,\n ssl=conninfo.ssl,\n connect_timeout=conninfo.connect_timeout)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef queue_exists(self, queue):\n try:\n self.channel.queue_declare(queue=queue, passive=True)\n except AMQPChannelException, e:\n if e.amqp_reply_code == 404:\n return False\n raise e\n else:\n return True", "response": "Check if a queue exists."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ndeleting a queue by name.", "response": "def queue_delete(self, queue, if_unused=False, if_empty=False):\n \"\"\"Delete queue by name.\"\"\"\n return self.channel.queue_delete(queue, if_unused, if_empty)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ndeclaring a named queue.", "response": "def queue_declare(self, queue, durable, exclusive, auto_delete,\n warn_if_exists=False, arguments=None):\n \"\"\"Declare a named queue.\"\"\"\n if warn_if_exists and self.queue_exists(queue):\n warnings.warn(QueueAlreadyExistsWarning(\n QueueAlreadyExistsWarning.__doc__))\n\n return self.channel.queue_declare(queue=queue,\n durable=durable,\n exclusive=exclusive,\n auto_delete=auto_delete,\n arguments=arguments)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ndeclare an named exchange.", "response": "def exchange_declare(self, exchange, type, durable, auto_delete):\n \"\"\"Declare an named exchange.\"\"\"\n return self.channel.exchange_declare(exchange=exchange,\n type=type,\n durable=durable,\n auto_delete=auto_delete)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef queue_bind(self, queue, exchange, routing_key, arguments=None):\n return self.channel.queue_bind(queue=queue,\n exchange=exchange,\n routing_key=routing_key,\n arguments=arguments)", "response": "Bind a queue to an exchange using a routing key."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get(self, queue, no_ack=False):\n raw_message = self.channel.basic_get(queue, no_ack=no_ack)\n if not raw_message:\n return None\n return self.message_to_python(raw_message)", "response": "Receive a message from a declared queue by name."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef consume(self, limit=None):\n for total_message_count in count():\n if limit and total_message_count >= limit:\n raise StopIteration\n\n if not self.channel.is_open:\n raise StopIteration\n\n self.channel.wait()\n yield True", "response": "Returns an iterator that waits for one message at a time."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef cancel(self, consumer_tag):\n if not self.channel.connection:\n return\n self.channel.basic_cancel(consumer_tag)", "response": "Cancel a channel by consumer tag."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nclose the channel if open.", "response": "def close(self):\n \"\"\"Close the channel if open.\"\"\"\n if self._channel and self._channel.is_open:\n self._channel.close()\n self._channel_ref = None"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nrequests specific Quality of Service.", "response": "def qos(self, prefetch_size, prefetch_count, apply_global=False):\n \"\"\"Request specific Quality of Service.\"\"\"\n self.channel.basic_qos(prefetch_size, prefetch_count,\n apply_global)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef channel(self):\n if not self._channel:\n self._channel_ref = weakref.ref(self.connection.get_channel())\n return self._channel", "response": "Returns the channel object."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nestablishes connection to the AMQP broker.", "response": "def establish_connection(self):\n \"\"\"Establish connection to the AMQP broker.\"\"\"\n conninfo = self.connection\n if not conninfo.hostname:\n raise KeyError(\"Missing hostname for AMQP connection.\")\n if conninfo.userid is None:\n raise KeyError(\"Missing user id for AMQP connection.\")\n if conninfo.password is None:\n raise KeyError(\"Missing password for AMQP connection.\")\n if not conninfo.port:\n conninfo.port = self.default_port\n conn = amqp.Connection(host=conninfo.hostname,\n port=conninfo.port,\n userid=conninfo.userid,\n password=conninfo.password,\n virtual_host=conninfo.virtual_host)\n return conn"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning an iterator that waits for one message at a time.", "response": "def consume(self, limit=None):\n \"\"\"Returns an iterator that waits for one message at a time.\"\"\"\n for total_message_count in count():\n if limit and total_message_count >= limit:\n raise StopIteration\n\n if not self.channel.is_open:\n raise StopIteration\n\n self.channel.conn.drain_events()\n yield True"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncancels a channel by consumer tag.", "response": "def cancel(self, consumer_tag):\n \"\"\"Cancel a channel by consumer tag.\"\"\"\n if not self.channel.conn:\n return\n self.channel.basic_cancel(consumer_tag)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef prepare_message(self, message_data, delivery_mode, priority=None,\n content_type=None, content_encoding=None):\n \"\"\"Encapsulate data into a AMQP message.\"\"\"\n return amqp.Message(message_data, properties={\n \"delivery_mode\": delivery_mode,\n \"priority\": priority,\n \"content_type\": content_type,\n \"content_encoding\": content_encoding})", "response": "Encapsulate data into a AMQP message."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef register_json():\n from anyjson import serialize as json_serialize\n from anyjson import deserialize as json_deserialize\n\n registry.register('json', json_serialize, json_deserialize,\n content_type='application/json',\n content_encoding='utf-8')", "response": "Register a encoder or decoder for JSON serialization."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nregistering a encoder and decoder for YAML serialization.", "response": "def register_yaml():\n \"\"\"Register a encoder/decoder for YAML serialization.\n\n It is slower than JSON, but allows for more data types\n to be serialized. Useful if you need to send data such as dates\"\"\"\n try:\n import yaml\n registry.register('yaml', yaml.safe_dump, yaml.safe_load,\n content_type='application/x-yaml',\n content_encoding='utf-8')\n except ImportError:\n\n def not_available(*args, **kwargs):\n \"\"\"In case a client receives a yaml message, but yaml\n isn't installed.\"\"\"\n raise SerializerNotInstalled(\n \"No decoder installed for YAML. Install the PyYAML library\")\n registry.register('yaml', None, not_available, 'application/x-yaml')"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nregistering msgpack with the msgpack library.", "response": "def register_msgpack():\n \"\"\"See http://msgpack.sourceforge.net/\"\"\"\n try:\n import msgpack\n registry.register('msgpack', msgpack.packs, msgpack.unpacks,\n content_type='application/x-msgpack',\n content_encoding='binary')\n except ImportError:\n\n def not_available(*args, **kwargs):\n \"\"\"In case a client receives a msgpack message, but yaml\n isn't installed.\"\"\"\n raise SerializerNotInstalled(\n \"No decoder installed for msgpack. \"\n \"Install the msgpack library\")\n registry.register('msgpack', None, not_available,\n 'application/x-msgpack')"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef register(self, name, encoder, decoder, content_type,\n content_encoding='utf-8'):\n \"\"\"Register a new encoder/decoder.\n\n :param name: A convenience name for the serialization method.\n\n :param encoder: A method that will be passed a python data structure\n and should return a string representing the serialized data.\n If ``None``, then only a decoder will be registered. Encoding\n will not be possible.\n\n :param decoder: A method that will be passed a string representing\n serialized data and should return a python data structure.\n If ``None``, then only an encoder will be registered.\n Decoding will not be possible.\n\n :param content_type: The mime-type describing the serialized\n structure.\n\n :param content_encoding: The content encoding (character set) that\n the :param:`decoder` method will be returning. Will usually be\n ``utf-8``, ``us-ascii``, or ``binary``.\n\n \"\"\"\n if encoder:\n self._encoders[name] = (content_type, content_encoding, encoder)\n if decoder:\n self._decoders[content_type] = decoder", "response": "Register a new encoder and decoder for a new version of the object."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _set_default_serializer(self, name):\n try:\n (self._default_content_type, self._default_content_encoding,\n self._default_encode) = self._encoders[name]\n except KeyError:\n raise SerializerNotInstalled(\n \"No encoder installed for %s\" % name)", "response": "Sets the default serialization method used by this library."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef encode(self, data, serializer=None):\n if serializer == \"raw\":\n return raw_encode(data)\n if serializer and not self._encoders.get(serializer):\n raise SerializerNotInstalled(\n \"No encoder installed for %s\" % serializer)\n\n # If a raw string was sent, assume binary encoding\n # (it's likely either ASCII or a raw binary file, but 'binary'\n # charset will encompass both, even if not ideal.\n if not serializer and isinstance(data, str):\n # In Python 3+, this would be \"bytes\"; allow binary data to be\n # sent as a message without getting encoder errors\n return \"application/data\", \"binary\", data\n\n # For unicode objects, force it into a string\n if not serializer and isinstance(data, unicode):\n payload = data.encode(\"utf-8\")\n return \"text/plain\", \"utf-8\", payload\n\n if serializer:\n content_type, content_encoding, encoder = \\\n self._encoders[serializer]\n else:\n encoder = self._default_encode\n content_type = self._default_content_type\n content_encoding = self._default_content_encoding\n\n payload = encoder(data)\n return content_type, content_encoding, payload", "response": "Encodes a data structure into a string suitable for sending to the broker."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef decode(self, data, content_type, content_encoding):\n content_type = content_type or 'application/data'\n content_encoding = (content_encoding or 'utf-8').lower()\n\n # Don't decode 8-bit strings or unicode objects\n if content_encoding not in ('binary', 'ascii-8bit') and \\\n not isinstance(data, unicode):\n data = codecs.decode(data, content_encoding)\n\n try:\n decoder = self._decoders[content_type]\n except KeyError:\n return data\n\n return decoder(data)", "response": "Deserialize a data stream as serialized using encode based on content_type and content_encoding."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nacknowledging this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected.", "response": "def ack(self):\n \"\"\"Acknowledge this message as being processed.,\n This will remove the message from the queue.\n\n :raises MessageStateError: If the message has already been\n acknowledged/requeued/rejected.\n\n \"\"\"\n if self.acknowledged:\n raise self.MessageStateError(\n \"Message already acknowledged with state: %s\" % self._state)\n self.backend.ack(self._frame)\n self._state = \"ACK\""}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn an iterator that waits for one message at a time.", "response": "def consume(self, limit=None):\n \"\"\"Returns an iterator that waits for one message at a time.\"\"\"\n for total_message_count in count():\n if limit and total_message_count >= limit:\n raise StopIteration\n self.drain_events()\n yield True"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncreates a randomly generated bit string of the given length with the probability of bit_prob equal to bit_prob.", "response": "def random(cls, length, bit_prob=.5):\n \"\"\"Create a bit string of the given length, with the probability of\n each bit being set equal to bit_prob, which defaults to .5.\n\n Usage:\n # Create a random BitString of length 10 with mostly zeros.\n bits = BitString.random(10, bit_prob=.1)\n\n Arguments:\n length: An int, indicating the desired length of the result.\n bit_prob: A float in the range [0, 1]. This is the probability\n of any given bit in the result having a value of 1; default\n is .5, giving 0 and 1 equal probabilities of appearance for\n each bit's value.\n Return:\n A randomly generated BitString instance of the requested\n length.\n \"\"\"\n\n assert isinstance(length, int) and length >= 0\n assert isinstance(bit_prob, (int, float)) and 0 <= bit_prob <= 1\n\n bits = numpy.random.choice(\n [False, True],\n size=(length,),\n p=[1-bit_prob, bit_prob]\n )\n bits.flags.writeable = False\n\n return cls(bits)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef crossover_template(cls, length, points=2):\n\n assert isinstance(length, int) and length >= 0\n assert isinstance(points, int) and points >= 0\n\n # Select the crossover points.\n points = random.sample(range(length + 1), points)\n\n # Prep the points for the loop.\n points.sort()\n points.append(length)\n\n # Fill the bits in with alternating ranges of 0 and 1 according to\n # the selected crossover points.\n previous = 0\n include_range = bool(random.randrange(2))\n pieces = []\n for point in points:\n if point > previous:\n fill = (numpy.ones if include_range else numpy.zeros)\n pieces.append(fill(point - previous, dtype=bool))\n include_range = not include_range\n previous = point\n bits = numpy.concatenate(pieces)\n bits.flags.writeable = False\n\n return cls(bits)", "response": "Create a crossover template with the given number of points."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef cover(cls, bits, wildcard_probability):\n\n if not isinstance(bits, BitString):\n bits = BitString(bits)\n\n mask = BitString([\n random.random() > wildcard_probability\n for _ in range(len(bits))\n ])\n\n return cls(bits, mask)", "response": "Create a new bit condition that matches the provided bit string with the indicated per - index wildcard probability."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nperforming 2 - point crossover on this bit condition and another bit condition.", "response": "def crossover_with(self, other, points=2):\n \"\"\"Perform 2-point crossover on this bit condition and another of\n the same length, returning the two resulting children.\n\n Usage:\n offspring1, offspring2 = condition1.crossover_with(condition2)\n\n Arguments:\n other: A second BitCondition of the same length as this one.\n points: An int, the number of crossover points of the\n crossover operation.\n Return:\n A tuple (condition1, condition2) of BitConditions, where the\n value at each position of this BitCondition and the other is\n preserved in one or the other of the two resulting conditions.\n \"\"\"\n\n assert isinstance(other, BitCondition)\n assert len(self) == len(other)\n\n template = BitString.crossover_template(len(self), points)\n inv_template = ~template\n\n bits1 = (self._bits & template) | (other._bits & inv_template)\n mask1 = (self._mask & template) | (other._mask & inv_template)\n\n bits2 = (self._bits & inv_template) | (other._bits & template)\n mask2 = (self._mask & inv_template) | (other._mask & template)\n\n # Convert the modified sequences back into BitConditions\n return type(self)(bits1, mask1), type(self)(bits2, mask2)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_backend_cls(self):\n backend_cls = self.backend_cls\n if not backend_cls or isinstance(backend_cls, basestring):\n backend_cls = get_backend_cls(backend_cls)\n return backend_cls", "response": "Get the currently used backend class."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef ensure_connection(self, errback=None, max_retries=None,\n interval_start=2, interval_step=2, interval_max=30):\n \"\"\"Ensure we have a connection to the server.\n\n If not retry establishing the connection with the settings\n specified.\n\n :keyword errback: Optional callback called each time the connection\n can't be established. Arguments provided are the exception\n raised and the interval that will be slept ``(exc, interval)``.\n\n :keyword max_retries: Maximum number of times to retry.\n If this limit is exceeded the connection error will be re-raised.\n\n :keyword interval_start: The number of seconds we start sleeping for.\n :keyword interval_step: How many seconds added to the interval\n for each retry.\n :keyword interval_max: Maximum number of seconds to sleep between\n each retry.\n\n \"\"\"\n retry_over_time(self.connect, self.connection_errors, (), {},\n errback, max_retries,\n interval_start, interval_step, interval_max)\n return self", "response": "Ensure we have a connection to the server."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef close(self):\n try:\n if self._connection:\n backend = self.create_backend()\n backend.close_connection(self._connection)\n except socket.error:\n pass\n self._closed = True", "response": "Close the currently open connection."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef decode(self):\n return serialization.decode(self.body, self.content_type,\n self.content_encoding)", "response": "Deserialize the message body returning the original\n python structure sent by the publisher."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef ack(self):\n if self.acknowledged:\n raise self.MessageStateError(\n \"Message already acknowledged with state: %s\" % self._state)\n self.backend.ack(self.delivery_tag)\n self._state = \"ACK\"", "response": "Acknowledge this message as being processed.,\n This will remove the message from the queue.\n\n :raises MessageStateError: If the message has already been\n acknowledged/requeued/rejected."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef reject(self):\n if self.acknowledged:\n raise self.MessageStateError(\n \"Message already acknowledged with state: %s\" % self._state)\n self.backend.reject(self.delivery_tag)\n self._state = \"REJECTED\"", "response": "Reject this message.\n\n The message will be discarded by the server.\n\n :raises MessageStateError: If the message has already been\n acknowledged/requeued/rejected."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef requeue(self):\n if self.acknowledged:\n raise self.MessageStateError(\n \"Message already acknowledged with state: %s\" % self._state)\n self.backend.requeue(self.delivery_tag)\n self._state = \"REQUEUED\"", "response": "Reject this message and put it back on the queue."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ngenerates a unique id for a node.", "response": "def gen_unique_id():\n \"\"\"Generate a unique id, having - hopefully - a very small chance of\n collission.\n\n For now this is provided by :func:`uuid.uuid4`.\n \"\"\"\n # Workaround for http://bugs.python.org/issue4607\n if ctypes and _uuid_generate_random:\n buffer = ctypes.create_string_buffer(16)\n _uuid_generate_random(buffer)\n return str(UUID(bytes=buffer.raw))\n return str(uuid4())"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef retry_over_time(fun, catch, args=[], kwargs={}, errback=None,\n max_retries=None, interval_start=2, interval_step=2, interval_max=30):\n \"\"\"Retry the function over and over until max retries is exceeded.\n\n For each retry we sleep a for a while before we try again, this interval\n is increased for every retry until the max seconds is reached.\n\n :param fun: The function to try\n :param catch: Exceptions to catch, can be either tuple or a single\n exception class.\n :keyword args: Positional arguments passed on to the function.\n :keyword kwargs: Keyword arguments passed on to the function.\n :keyword errback: Callback for when an exception in ``catch`` is raised.\n The callback must take two arguments: ``exc`` and ``interval``, where\n ``exc`` is the exception instance, and ``interval`` is the time in\n seconds to sleep next..\n :keyword max_retries: Maximum number of retries before we give up.\n If this is not set, we will retry forever.\n :keyword interval_start: How long (in seconds) we start sleeping between\n retries.\n :keyword interval_step: By how much the interval is increased for each\n retry.\n :keyword interval_max: Maximum number of seconds to sleep between retries.\n\n \"\"\"\n retries = 0\n interval_range = xrange(interval_start,\n interval_max + interval_start,\n interval_step)\n\n for retries, interval in enumerate(repeatlast(interval_range)):\n try:\n retval = fun(*args, **kwargs)\n except catch, exc:\n if max_retries and retries > max_retries:\n raise\n if errback:\n errback(exc, interval)\n sleep(interval)\n else:\n return retval", "response": "Retry the function over and over time."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nget the next waiting message from the queue.", "response": "def get(self, *args, **kwargs):\n \"\"\"Get the next waiting message from the queue.\n\n :returns: A :class:`Message` instance, or ``None`` if there is\n no messages waiting.\n\n \"\"\"\n if not mqueue.qsize():\n return None\n message_data, content_type, content_encoding = mqueue.get()\n return self.Message(backend=self, body=message_data,\n content_type=content_type,\n content_encoding=content_encoding)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ndiscarding all messages in the queue.", "response": "def queue_purge(self, queue, **kwargs):\n \"\"\"Discard all messages in the queue.\"\"\"\n qsize = mqueue.qsize()\n mqueue.queue.clear()\n return qsize"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef prepare_message(self, message_data, delivery_mode,\n content_type, content_encoding, **kwargs):\n \"\"\"Prepare message for sending.\"\"\"\n return (message_data, content_type, content_encoding)", "response": "Prepare message for sending."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns the expected near - future payoff for the currently selected action given only the current match set.", "response": "def get_future_expectation(self, match_set):\n \"\"\"Return a numerical value representing the expected future payoff\n of the previously selected action, given only the current match\n set. The match_set argument is a MatchSet instance representing the\n current match set.\n\n Usage:\n match_set = model.match(situation)\n expectation = model.algorithm.get_future_expectation(match_set)\n payoff = previous_reward + discount_factor * expectation\n previous_match_set.payoff = payoff\n\n Arguments:\n match_set: A MatchSet instance.\n Return:\n A float, the estimate of the expected near-future payoff for\n the situation for which match_set was generated, based on the\n contents of match_set.\n \"\"\"\n assert isinstance(match_set, MatchSet)\n assert match_set.algorithm is self\n\n return self.discount_factor * (\n self.idealization_factor * match_set.best_prediction +\n (1 - self.idealization_factor) * match_set.prediction\n )"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn a Boolean indicating whether covering is required for the current match set.", "response": "def covering_is_required(self, match_set):\n \"\"\"Return a Boolean indicating whether covering is required for the\n current match set. The match_set argument is a MatchSet instance\n representing the current match set before covering is applied.\n\n Usage:\n match_set = model.match(situation)\n if model.algorithm.covering_is_required(match_set):\n new_rule = model.algorithm.cover(match_set)\n assert new_rule.condition(situation)\n model.add(new_rule)\n match_set = model.match(situation)\n\n Arguments:\n match_set: A MatchSet instance.\n Return:\n A bool indicating whether match_set contains too few matching\n classifier rules and therefore needs to be augmented with a\n new one.\n \"\"\"\n assert isinstance(match_set, MatchSet)\n assert match_set.algorithm is self\n\n if self.minimum_actions is None:\n return len(match_set) < len(match_set.model.possible_actions)\n else:\n return len(match_set) < self.minimum_actions"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns a new classifier rule that can be added to the match set with a condition that matches the situation of the match set and an action that is not already suggested by the actions already contained therein.", "response": "def cover(self, match_set):\n \"\"\"Return a new classifier rule that can be added to the match set,\n with a condition that matches the situation of the match set and an\n action selected to avoid duplication of the actions already\n contained therein. The match_set argument is a MatchSet instance\n representing the match set to which the returned rule may be added.\n\n Usage:\n match_set = model.match(situation)\n if model.algorithm.covering_is_required(match_set):\n new_rule = model.algorithm.cover(match_set)\n assert new_rule.condition(situation)\n model.add(new_rule)\n match_set = model.match(situation)\n\n Arguments:\n match_set: A MatchSet instance.\n Return:\n A new ClassifierRule instance, appropriate for the addition to\n match_set and to the classifier set from which match_set was\n drawn.\n \"\"\"\n\n assert isinstance(match_set, MatchSet)\n assert match_set.model.algorithm is self\n\n # Create a new condition that matches the situation.\n condition = bitstrings.BitCondition.cover(\n match_set.situation,\n self.wildcard_probability\n )\n\n # Pick a random action that (preferably) isn't already suggested by\n # some other rule for this situation.\n action_candidates = (\n frozenset(match_set.model.possible_actions) -\n frozenset(match_set)\n )\n if not action_candidates:\n action_candidates = match_set.model.possible_actions\n action = random.choice(list(action_candidates))\n\n # Create the new rule.\n return XCSClassifierRule(\n condition,\n action,\n self,\n match_set.time_stamp\n )"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ndistributes the payoff received in response to the selected action of the given match set.", "response": "def distribute_payoff(self, match_set):\n \"\"\"Distribute the payoff received in response to the selected\n action of the given match set among the rules in the action set\n which deserve credit for recommending the action. The match_set\n argument is the MatchSet instance which suggested the selected\n action and earned the payoff.\n\n Usage:\n match_set = model.match(situation)\n match_set.select_action()\n match_set.payoff = reward\n model.algorithm.distribute_payoff(match_set)\n\n Arguments:\n match_set: A MatchSet instance for which the accumulated payoff\n needs to be distributed among its classifier rules.\n Return: None\n \"\"\"\n\n assert isinstance(match_set, MatchSet)\n assert match_set.algorithm is self\n assert match_set.selected_action is not None\n\n payoff = float(match_set.payoff)\n\n action_set = match_set[match_set.selected_action]\n action_set_size = sum(rule.numerosity for rule in action_set)\n\n # Update the average reward, error, and action set size of each\n # rule participating in the action set.\n for rule in action_set:\n rule.experience += 1\n\n update_rate = max(self.learning_rate, 1 / rule.experience)\n\n rule.average_reward += (\n (payoff - rule.average_reward) *\n update_rate\n )\n\n rule.error += (\n (abs(payoff - rule.average_reward) - rule.error) *\n update_rate\n\n )\n\n rule.action_set_size += (\n (action_set_size - rule.action_set_size) *\n update_rate\n )\n\n # Update the fitness of the rules.\n self._update_fitness(action_set)\n\n # If the parameters so indicate, perform action set subsumption.\n if self.do_action_set_subsumption:\n self._action_set_subsumption(action_set)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef update(self, match_set):\n\n assert isinstance(match_set, MatchSet)\n assert match_set.model.algorithm is self\n assert match_set.selected_action is not None\n\n # Increment the iteration counter.\n match_set.model.update_time_stamp()\n\n action_set = match_set[match_set.selected_action]\n\n # If the average number of iterations since the last update for\n # each rule in the action set is too small, return early instead of\n # applying the GA.\n average_time_passed = (\n match_set.model.time_stamp -\n self._get_average_time_stamp(action_set)\n )\n if average_time_passed <= self.ga_threshold:\n return\n\n # Update the time step for each rule to indicate that they were\n # updated by the GA.\n self._set_timestamps(action_set)\n\n # Select two parents from the action set, with probability\n # proportionate to their fitness.\n parent1 = self._select_parent(action_set)\n parent2 = self._select_parent(action_set)\n\n # With the probability specified in the parameters, apply the\n # crossover operator to the parents. Otherwise, just take the\n # parents unchanged.\n if random.random() < self.crossover_probability:\n condition1, condition2 = parent1.condition.crossover_with(\n parent2.condition\n )\n else:\n condition1, condition2 = parent1.condition, parent2.condition\n\n # Apply the mutation operator to each child, randomly flipping\n # their mask bits with a small probability.\n condition1 = self._mutate(condition1, action_set.situation)\n condition2 = self._mutate(condition2, action_set.situation)\n\n # If the newly generated children are already present in the\n # population (or if they should be subsumed due to GA subsumption)\n # then simply increment the numerosities of the existing rules in\n # the population.\n new_children = []\n for condition in condition1, condition2:\n # If the parameters specify that GA subsumption should be\n # performed, look for an accurate parent that can subsume the\n # new child.\n if self.do_ga_subsumption:\n subsumed = False\n for parent in parent1, parent2:\n should_subsume = (\n (parent.experience >\n self.subsumption_threshold) and\n parent.error < self.error_threshold and\n parent.condition(condition)\n )\n if should_subsume:\n if parent in action_set.model:\n parent.numerosity += 1\n self.prune(action_set.model)\n else:\n # Sometimes the parent is removed from a\n # previous subsumption\n parent.numerosity = 1\n action_set.model.add(parent)\n subsumed = True\n break\n if subsumed:\n continue\n\n # Provided the child has not already been subsumed and it is\n # present in the population, just increment its numerosity.\n # Otherwise, if the child has neither been subsumed nor does it\n # already exist, remember it so we can add it to the classifier\n # set in just a moment.\n child = XCSClassifierRule(\n condition,\n action_set.action,\n self,\n action_set.model.time_stamp\n )\n if child in action_set.model:\n action_set.model.add(child)\n else:\n new_children.append(child)\n\n # If there were any children which weren't subsumed and weren't\n # already present in the classifier set, add them.\n if new_children:\n average_reward = .5 * (\n parent1.average_reward +\n parent2.average_reward\n )\n\n error = .5 * (parent1.error + parent2.error)\n\n # .1 * (average fitness of parents)\n fitness = .05 * (\n parent1.fitness +\n parent2.fitness\n )\n\n for child in new_children:\n child.average_reward = average_reward\n child.error = error\n child.fitness = fitness\n action_set.model.add(child)", "response": "Update the classifier set from which the match set was drawn."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef prune(self, model):\n\n assert isinstance(model, ClassifierSet)\n assert model.algorithm is self\n\n # Determine the (virtual) population size.\n total_numerosity = sum(rule.numerosity for rule in model)\n\n # If the population size is already small enough, just return early\n if total_numerosity <= self.max_population_size:\n return [] # No rule's numerosity dropped to zero.\n\n # Determine the average fitness of the rules in the population.\n total_fitness = sum(rule.fitness for rule in model)\n average_fitness = total_fitness / total_numerosity\n\n # Determine the probability of deletion, as a function of both\n # accuracy and niche sparsity.\n total_votes = 0\n deletion_votes = {}\n for rule in model:\n vote = rule.action_set_size * rule.numerosity\n\n sufficient_experience = (\n rule.experience > self.deletion_threshold\n )\n low_fitness = (\n rule.fitness / rule.numerosity <\n self.fitness_threshold * average_fitness\n )\n if sufficient_experience and low_fitness:\n vote *= average_fitness / (rule.fitness /\n rule.numerosity)\n\n deletion_votes[rule] = vote\n total_votes += vote\n\n # Choose a rule to delete based on the probabilities just computed.\n selector = random.uniform(0, total_votes)\n for rule, vote in deletion_votes.items():\n selector -= vote\n if selector <= 0:\n assert rule in model\n if model.discard(rule):\n return [rule]\n else:\n return []\n\n assert False", "response": "Reduce the classifier set s population size by removing lower - quality rules. Return a list containing any rules that were removed entirely from the classifier set."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nupdating the fitness values of the rules belonging to this action_set.", "response": "def _update_fitness(self, action_set):\n \"\"\"Update the fitness values of the rules belonging to this action\n set.\"\"\"\n # Compute the accuracy of each rule. Accuracy is inversely\n # proportional to error. Below a certain error threshold, accuracy\n # becomes constant. Accuracy values range over (0, 1].\n total_accuracy = 0\n accuracies = {}\n for rule in action_set:\n if rule.error < self.error_threshold:\n accuracy = 1\n else:\n accuracy = (\n self.accuracy_coefficient *\n (rule.error / self.error_threshold) **\n -self.accuracy_power\n )\n accuracies[rule] = accuracy\n total_accuracy += accuracy * rule.numerosity\n\n # On rare occasions we have zero total accuracy. This avoids a div\n # by zero\n total_accuracy = total_accuracy or 1\n\n # Use the relative accuracies of the rules to update their fitness\n for rule in action_set:\n accuracy = accuracies[rule]\n rule.fitness += (\n self.learning_rate *\n (accuracy * rule.numerosity / total_accuracy -\n rule.fitness)\n )"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _action_set_subsumption(self, action_set):\n # Select a condition with maximum bit count among those having\n # sufficient experience and sufficiently low error.\n selected_rule = None\n selected_bit_count = None\n for rule in action_set:\n if not (rule.experience > self.subsumption_threshold and\n rule.error < self.error_threshold):\n continue\n bit_count = rule.condition.count()\n if (selected_rule is None or\n bit_count > selected_bit_count or\n (bit_count == selected_bit_count and\n random.randrange(2))):\n selected_rule = rule\n selected_bit_count = bit_count\n\n # If no rule was found satisfying the requirements, return\n # early.\n if selected_rule is None:\n return\n\n # Subsume each rule which the selected rule generalizes. When a\n # rule is subsumed, all instances of the subsumed rule are replaced\n # with instances of the more general one in the population.\n to_remove = []\n for rule in action_set:\n if (selected_rule is not rule and\n selected_rule.condition(rule.condition)):\n selected_rule.numerosity += rule.numerosity\n action_set.model.discard(rule, rule.numerosity)\n to_remove.append(rule)\n for rule in to_remove:\n action_set.remove(rule)", "response": "Perform action set subsumption."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _get_average_time_stamp(action_set):\n # This is the average value of the iteration counter upon the most\n # recent update of each rule in this action set.\n total_time_stamps = sum(rule.time_stamp * rule.numerosity\n for rule in action_set)\n total_numerosity = sum(rule.numerosity for rule in action_set)\n return total_time_stamps / (total_numerosity or 1)", "response": "Return the average time stamp for the rules in this action set."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nselects a rule from this action set with probability proportionate to its fitness to act as a parent for a new rule in the classifier set. Return the selected rule.", "response": "def _select_parent(action_set):\n \"\"\"Select a rule from this action set, with probability\n proportionate to its fitness, to act as a parent for a new rule in\n the classifier set. Return the selected rule.\"\"\"\n total_fitness = sum(rule.fitness for rule in action_set)\n selector = random.uniform(0, total_fitness)\n for rule in action_set:\n selector -= rule.fitness\n if selector <= 0:\n return rule\n # If for some reason a case slips through the above loop, perhaps\n # due to floating point error, we fall back on uniform selection.\n return random.choice(list(action_set))"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _mutate(self, condition, situation):\n\n # Go through each position in the condition, randomly flipping\n # whether the position is a value (0 or 1) or a wildcard (#). We do\n # this in a new list because the original condition's mask is\n # immutable.\n mutation_points = bitstrings.BitString.random(\n len(condition.mask),\n self.mutation_probability\n )\n mask = condition.mask ^ mutation_points\n\n # The bits that aren't wildcards always have the same value as the\n # situation, which ensures that the mutated condition still matches\n # the situation.\n if isinstance(situation, bitstrings.BitCondition):\n mask &= situation.mask\n return bitstrings.BitCondition(situation.bits, mask)\n return bitstrings.BitCondition(situation, mask)", "response": "Create a new condition from the given one by probabilistically applying point - wise mutations. Bits that were originally wildcarded\n in the parent condition acquire their values from the provided situation apply their values from the provided condition."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nestablish connection to the AMQP broker.", "response": "def establish_connection(self):\n \"\"\"Establish connection to the AMQP broker.\"\"\"\n conninfo = self.connection\n if not conninfo.port:\n conninfo.port = self.default_port\n credentials = pika.PlainCredentials(conninfo.userid,\n conninfo.password)\n return self._connection_cls(pika.ConnectionParameters(\n conninfo.hostname,\n port=conninfo.port,\n virtual_host=conninfo.virtual_host,\n credentials=credentials))"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ndiscarding all messages in the queue.", "response": "def queue_purge(self, queue, **kwargs):\n \"\"\"Discard all messages in the queue. This will delete the messages\n and results in an empty queue.\"\"\"\n return self.channel.queue_purge(queue=queue).message_count"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ndeclares a named queue.", "response": "def queue_declare(self, queue, durable, exclusive, auto_delete,\n warn_if_exists=False, arguments=None):\n \"\"\"Declare a named queue.\"\"\"\n\n return self.channel.queue_declare(queue=queue,\n durable=durable,\n exclusive=exclusive,\n auto_delete=auto_delete,\n arguments=arguments)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nclose the channel if open.", "response": "def close(self):\n \"\"\"Close the channel if open.\"\"\"\n if self._channel and not self._channel.handler.channel_close:\n self._channel.close()\n self._channel_ref = None"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nencapsulate data into a AMQP message.", "response": "def prepare_message(self, message_data, delivery_mode, priority=None,\n content_type=None, content_encoding=None):\n \"\"\"Encapsulate data into a AMQP message.\"\"\"\n properties = pika.BasicProperties(priority=priority,\n content_type=content_type,\n content_encoding=content_encoding,\n delivery_mode=delivery_mode)\n return message_data, properties"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\npublish a message to a named exchange.", "response": "def publish(self, message, exchange, routing_key, mandatory=None,\n immediate=None, headers=None):\n \"\"\"Publish a message to a named exchange.\"\"\"\n body, properties = message\n\n if headers:\n properties.headers = headers\n\n ret = self.channel.basic_publish(body=body,\n properties=properties,\n exchange=exchange,\n routing_key=routing_key,\n mandatory=mandatory,\n immediate=immediate)\n if mandatory or immediate:\n self.close()"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ngenerate a unique consumer tag.", "response": "def _generate_consumer_tag(self):\n \"\"\"Generate a unique consumer tag.\n\n :rtype string:\n\n \"\"\"\n return \"%s.%s%s\" % (\n self.__class__.__module__,\n self.__class__.__name__,\n self._next_consumer_tag())"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ndeclare the queue the exchange and binds the queue to the exchange.", "response": "def declare(self):\n \"\"\"Declares the queue, the exchange and binds the queue to\n the exchange.\"\"\"\n arguments = None\n routing_key = self.routing_key\n if self.exchange_type == \"headers\":\n arguments, routing_key = routing_key, \"\"\n\n if self.queue:\n self.backend.queue_declare(queue=self.queue, durable=self.durable,\n exclusive=self.exclusive,\n auto_delete=self.auto_delete,\n arguments=self.queue_arguments,\n warn_if_exists=self.warn_if_exists)\n if self.exchange:\n self.backend.exchange_declare(exchange=self.exchange,\n type=self.exchange_type,\n durable=self.durable,\n auto_delete=self.auto_delete)\n if self.queue:\n self.backend.queue_bind(queue=self.queue,\n exchange=self.exchange,\n routing_key=routing_key,\n arguments=arguments)\n self._closed = False\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef fetch(self, no_ack=None, auto_ack=None, enable_callbacks=False):\n no_ack = no_ack or self.no_ack\n auto_ack = auto_ack or self.auto_ack\n message = self.backend.get(self.queue, no_ack=no_ack)\n if message:\n if auto_ack and not message.acknowledged:\n message.ack()\n if enable_callbacks:\n self.receive(message.payload, message)\n return message", "response": "Fetch the next message waiting on the queue."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ndiscard all waiting messages.", "response": "def discard_all(self, filterfunc=None):\n \"\"\"Discard all waiting messages.\n\n :param filterfunc: A filter function to only discard the messages this\n filter returns.\n\n :returns: the number of messages discarded.\n\n *WARNING*: All incoming messages will be ignored and not processed.\n\n Example using filter:\n\n >>> def waiting_feeds_only(message):\n ... try:\n ... message_data = message.decode()\n ... except: # Should probably be more specific.\n ... pass\n ...\n ... if message_data.get(\"type\") == \"feed\":\n ... return True\n ... else:\n ... return False\n \"\"\"\n if not filterfunc:\n return self.backend.queue_purge(self.queue)\n\n if self.no_ack or self.auto_ack:\n raise Exception(\"discard_all: Can't use filter with auto/no-ack.\")\n\n discarded_count = 0\n while True:\n message = self.fetch()\n if message is None:\n return discarded_count\n\n if filterfunc(message):\n message.ack()\n discarded_count += 1"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngoes into consume mode.", "response": "def wait(self, limit=None):\n \"\"\"Go into consume mode.\n\n Mostly for testing purposes and simple programs, you probably\n want :meth:`iterconsume` or :meth:`iterqueue` instead.\n\n This runs an infinite loop, processing all incoming messages\n using :meth:`receive` to apply the message to all registered\n callbacks.\n\n \"\"\"\n it = self.iterconsume(limit)\n while True:\n it.next()"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef iterqueue(self, limit=None, infinite=False):\n for items_since_start in count():\n item = self.fetch()\n if (not infinite and item is None) or \\\n (limit and items_since_start >= limit):\n raise StopIteration\n yield item", "response": "Infinite iterator yielding pending messages from the queue."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncancel a running : meth : iterconsume session.", "response": "def cancel(self):\n \"\"\"Cancel a running :meth:`iterconsume` session.\"\"\"\n if self.channel_open:\n try:\n self.backend.cancel(self.consumer_tag)\n except KeyError:\n pass"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncloses the channel to the queue.", "response": "def close(self):\n \"\"\"Close the channel to the queue.\"\"\"\n self.cancel()\n self.backend.close()\n self._closed = True"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef qos(self, prefetch_size=0, prefetch_count=0, apply_global=False):\n return self.backend.qos(prefetch_size, prefetch_count, apply_global)", "response": "Request specific Quality of Service."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef declare(self):\n self.backend.exchange_declare(exchange=self.exchange,\n type=self.exchange_type,\n durable=self.durable,\n auto_delete=self.auto_delete)", "response": "Declare the exchange on the broker."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef create_message(self, message_data, delivery_mode=None, priority=None,\n content_type=None, content_encoding=None,\n serializer=None):\n \"\"\"With any data, serialize it and encapsulate it in a AMQP\n message with the proper headers set.\"\"\"\n\n delivery_mode = delivery_mode or self.delivery_mode\n\n # No content_type? Then we're serializing the data internally.\n if not content_type:\n serializer = serializer or self.serializer\n (content_type, content_encoding,\n message_data) = serialization.encode(message_data,\n serializer=serializer)\n else:\n # If the programmer doesn't want us to serialize,\n # make sure content_encoding is set.\n if isinstance(message_data, unicode):\n if not content_encoding:\n content_encoding = 'utf-8'\n message_data = message_data.encode(content_encoding)\n\n # If they passed in a string, we can't know anything\n # about it. So assume it's binary data.\n elif not content_encoding:\n content_encoding = 'binary'\n\n return self.backend.prepare_message(message_data, delivery_mode,\n priority=priority,\n content_type=content_type,\n content_encoding=content_encoding)", "response": "Create a new AMQP message."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef send(self, message_data, routing_key=None, delivery_mode=None,\n mandatory=False, immediate=False, priority=0, content_type=None,\n content_encoding=None, serializer=None, exchange=None):\n \"\"\"Send a message.\n\n :param message_data: The message data to send. Can be a list,\n dictionary or a string.\n\n :keyword routing_key: A custom routing key for the message.\n If not set, the default routing key set in the :attr:`routing_key`\n attribute is used.\n\n :keyword mandatory: If set, the message has mandatory routing.\n By default the message is silently dropped by the server if it\n can't be routed to a queue. However - If the message is mandatory,\n an exception will be raised instead.\n\n :keyword immediate: Request immediate delivery.\n If the message cannot be routed to a queue consumer immediately,\n an exception will be raised. This is instead of the default\n behaviour, where the server will accept and queue the message,\n but with no guarantee that the message will ever be consumed.\n\n :keyword delivery_mode: Override the default :attr:`delivery_mode`.\n\n :keyword priority: The message priority, ``0`` to ``9``.\n\n :keyword content_type: The messages content_type. If content_type\n is set, no serialization occurs as it is assumed this is either\n a binary object, or you've done your own serialization.\n Leave blank if using built-in serialization as our library\n properly sets content_type.\n\n :keyword content_encoding: The character set in which this object\n is encoded. Use \"binary\" if sending in raw binary objects.\n Leave blank if using built-in serialization as our library\n properly sets content_encoding.\n\n :keyword serializer: Override the default :attr:`serializer`.\n\n :keyword exchange: Override the exchange to publish to.\n Note that this exchange must have been declared.\n\n \"\"\"\n headers = None\n routing_key = routing_key or self.routing_key\n\n if self.exchange_type == \"headers\":\n headers, routing_key = routing_key, \"\"\n\n exchange = exchange or self.exchange\n\n message = self.create_message(message_data, priority=priority,\n delivery_mode=delivery_mode,\n content_type=content_type,\n content_encoding=content_encoding,\n serializer=serializer)\n self.backend.publish(message,\n exchange=exchange, routing_key=routing_key,\n mandatory=mandatory, immediate=immediate,\n headers=headers)", "response": "Sends a message to the specified exchange."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsending a message to the topic.", "response": "def send(self, message_data, delivery_mode=None):\n \"\"\"See :meth:`Publisher.send`\"\"\"\n self.publisher.send(message_data, delivery_mode=delivery_mode)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef close(self):\n self.consumer.close()\n self.publisher.close()\n self._closed = True", "response": "Close any open channels."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _receive_callback(self, raw_message):\n message = self.backend.message_to_python(raw_message)\n if self.auto_ack and not message.acknowledged:\n message.ack()\n try:\n decoded = message.decode()\n except Exception, exc:\n if not self.on_decode_error:\n raise\n self.on_decode_error(message, exc)\n else:\n self.receive(decoded, message)", "response": "Internal method used when a message is received in consume mode."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nadds another consumer from dictionary configuration.", "response": "def add_consumer_from_dict(self, queue, **options):\n \"\"\"Add another consumer from dictionary configuration.\"\"\"\n options.setdefault(\"routing_key\", options.pop(\"binding_key\", None))\n consumer = Consumer(self.connection, queue=queue,\n backend=self.backend, **options)\n self.consumers.append(consumer)\n return consumer"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef add_consumer(self, consumer):\n consumer.backend = self.backend\n self.consumers.append(consumer)", "response": "Add another consumer from a : class : Consumer instance."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ndeclares consumer so messages can be received from it using .", "response": "def _declare_consumer(self, consumer, nowait=False):\n \"\"\"Declare consumer so messages can be received from it using\n :meth:`iterconsume`.\"\"\"\n if consumer.queue not in self._open_consumers:\n # Use the ConsumerSet's consumer by default, but if the\n # child consumer has a callback, honor it.\n callback = consumer.callbacks and \\\n consumer._receive_callback or self._receive_callback\n self.backend.declare_consumer(queue=consumer.queue,\n no_ack=consumer.no_ack,\n nowait=nowait,\n callback=callback,\n consumer_tag=consumer.consumer_tag)\n self._open_consumers[consumer.queue] = consumer.consumer_tag"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef iterconsume(self, limit=None):\n self.consume()\n return self.backend.consume(limit=limit)", "response": "Iterate over all consumers in consume mode."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef cancel(self):\n for consumer_tag in self._open_consumers.values():\n try:\n self.backend.cancel(consumer_tag)\n except KeyError:\n pass\n self._open_consumers.clear()", "response": "Cancel a running : meth : iterconsume session."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef convert_md_to_rst(source, destination=None, backup_dir=None):\n\n # Doing this in the function instead of the module level ensures the\n # error occurs when the function is called, rather than when the module\n # is evaluated.\n try:\n import pypandoc\n except ImportError:\n # Don't give up right away; first try to install the python module.\n os.system(\"pip install pypandoc\")\n import pypandoc\n\n # Set our destination path to a default, if necessary\n destination = destination or (os.path.splitext(source)[0] + '.rst')\n\n # Likewise for the backup directory\n backup_dir = backup_dir or os.path.join(os.path.dirname(destination),\n 'bak')\n\n bak_name = (os.path.basename(destination) +\n time.strftime('.%Y%m%d%H%M%S.bak'))\n bak_path = os.path.join(backup_dir, bak_name)\n\n # If there's already a file at the destination path, move it out of the\n # way, but don't delete it.\n if os.path.isfile(destination):\n if not os.path.isdir(os.path.dirname(bak_path)):\n os.mkdir(os.path.dirname(bak_path))\n os.rename(destination, bak_path)\n\n try:\n # Try to convert the file.\n pypandoc.convert(\n source,\n 'rst',\n format='md',\n outputfile=destination\n )\n except:\n # If for any reason the conversion fails, try to put things back\n # like we found them.\n if os.path.isfile(destination):\n os.remove(destination)\n if os.path.isfile(bak_path):\n os.rename(bak_path, destination)\n raise", "response": "Try to convert the source file to an. rst file at the destination."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ncalls the conversion routine on README. md to generate README. rst.", "response": "def build_readme(base_path=None):\n \"\"\"Call the conversion routine on README.md to generate README.rst.\n Why do all this? Because pypi requires reStructuredText, but markdown\n is friendlier to work with and is nicer for GitHub.\"\"\"\n if base_path:\n path = os.path.join(base_path, 'README.md')\n else:\n path = 'README.md'\n convert_md_to_rst(path)\n print(\"Successfully converted README.md to README.rst\")"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef sense(self):\n self.current_situation = bitstrings.BitString([\n random.randrange(2)\n for _ in range(self.address_size + (1 << self.address_size))\n ])\n return self.current_situation", "response": "Return a situation encoded as a bit string which represents\n the observable state of the environment."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef execute(self, action):\n\n assert action in self.possible_actions\n\n self.remaining_cycles -= 1\n index = int(bitstrings.BitString(\n self.current_situation[:self.address_size]\n ))\n bit = self.current_situation[self.address_size + index]\n return action == bit", "response": "Execute the indicated action within the environment and return the resulting immediate reward dictated by the program."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nresets the scenario starting it over for a new run.", "response": "def reset(self):\n \"\"\"Reset the scenario, starting it over for a new run.\n\n Usage:\n if not scenario.more():\n scenario.reset()\n\n Arguments: None\n Return: None\n \"\"\"\n self.remaining_cycles = self.initial_training_cycles\n self.needle_index = random.randrange(self.input_size)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef sense(self):\n haystack = bitstrings.BitString.random(self.input_size)\n self.needle_value = haystack[self.needle_index]\n return haystack", "response": "Return a situation encoded as a bit string which represents\n the observable state of the environment."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nexecute the indicated action within the environment and return the resulting immediate reward dictated by the rewardPython program.", "response": "def execute(self, action):\n \"\"\"Execute the indicated action within the environment and\n return the resulting immediate reward dictated by the reward\n program.\n\n Usage:\n immediate_reward = scenario.execute(selected_action)\n\n Arguments:\n action: The action to be executed within the current situation.\n Return:\n A float, the reward received for the action that was executed,\n or None if no reward is offered.\n \"\"\"\n\n assert action in self.possible_actions\n\n self.remaining_cycles -= 1\n return action == self.needle_value"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a sequence containing the possible actions that can be executed within the environment.", "response": "def get_possible_actions(self):\n \"\"\"Return a sequence containing the possible actions that can be\n executed within the environment.\n\n Usage:\n possible_actions = scenario.get_possible_actions()\n\n Arguments: None\n Return:\n A sequence containing the possible actions which can be\n executed within this scenario.\n \"\"\"\n possible_actions = self.wrapped.get_possible_actions()\n\n if len(possible_actions) <= 20:\n # Try to ensure that the possible actions are unique. Also, put\n # them into a list so we can iterate over them safely before\n # returning them; this avoids accidentally exhausting an\n # iterator, if the wrapped class happens to return one.\n try:\n possible_actions = list(set(possible_actions))\n except TypeError:\n possible_actions = list(possible_actions)\n\n try:\n possible_actions.sort()\n except TypeError:\n pass\n\n self.logger.info('Possible actions:')\n for action in possible_actions:\n self.logger.info(' %s', action)\n else:\n self.logger.info(\"%d possible actions.\", len(possible_actions))\n\n return possible_actions"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef sense(self):\n situation = self.wrapped.sense()\n\n self.logger.debug('Situation: %s', situation)\n\n return situation", "response": "Return a situation encoded as a bit string which represents\n the observable state of the environment."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nexecuting the indicated action within the environment and return the resulting immediate reward.", "response": "def execute(self, action):\n \"\"\"Execute the indicated action within the environment and\n return the resulting immediate reward dictated by the reward\n program.\n\n Usage:\n immediate_reward = scenario.execute(selected_action)\n\n Arguments:\n action: The action to be executed within the current situation.\n Return:\n A float, the reward received for the action that was executed,\n or None if no reward is offered.\n \"\"\"\n\n self.logger.debug('Executing action: %s', action)\n\n reward = self.wrapped.execute(action)\n if reward:\n self.total_reward += reward\n self.steps += 1\n\n self.logger.debug('Reward received on this step: %.5f',\n reward or 0)\n self.logger.debug('Average reward per step: %.5f',\n self.total_reward / self.steps)\n\n return reward"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef more(self):\n more = self.wrapped.more()\n\n if not self.steps % 100:\n self.logger.info('Steps completed: %d', self.steps)\n self.logger.info('Average reward per step: %.5f',\n self.total_reward / (self.steps or 1))\n if not more:\n self.logger.info('Run completed.')\n self.logger.info('Total steps: %d', self.steps)\n self.logger.info('Total reward received: %.5f',\n self.total_reward)\n self.logger.info('Average reward per step: %.5f',\n self.total_reward / (self.steps or 1))\n\n return more", "response": "Return a Boolean indicating whether additional situations may be executed in the current run."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef execute(self, action):\n reward = self.reward_function(\n action,\n self.classifications[self.steps]\n )\n self.total_reward += reward\n self.steps += 1\n return reward", "response": "Execute the indicated action within the environment and return the resulting immediate reward dictated by the reward_function."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_classifications(self):\n if bitstrings.using_numpy():\n return numpy.array(self.classifications)\n else:\n return self.classifications", "response": "Returns the classifications made by the algorithm for this\n scenario."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef new_model(self, scenario):\n assert isinstance(scenario, scenarios.Scenario)\n return ClassifierSet(self, scenario.get_possible_actions())", "response": "Create and return a new untrained classifier set initialized for handling\n the given scenario."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef run(self, scenario):\n assert isinstance(scenario, scenarios.Scenario)\n model = self.new_model(scenario)\n model.run(scenario, learn=True)\n return model", "response": "Run the algorithm and return a classifier set that was trained on the given scenario."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncomputes the combined prediction and prediction weight for thisCOOKIE.", "response": "def _compute_prediction(self):\n \"\"\"Compute the combined prediction and prediction weight for this\n action set. The combined prediction is the weighted average of the\n individual predictions of the classifiers. The combined prediction\n weight is the sum of the individual prediction weights of the\n classifiers.\n\n Usage:\n Do not call this method directly. Use the prediction and/or\n prediction_weight properties instead.\n\n Arguments: None\n Return: None\n \"\"\"\n total_weight = 0\n total_prediction = 0\n for rule in self._rules.values():\n total_weight += rule.prediction_weight\n total_prediction += (rule.prediction *\n rule.prediction_weight)\n self._prediction = total_prediction / (total_weight or 1)\n self._prediction_weight = total_weight"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef best_prediction(self):\n if self._best_prediction is None and self._action_sets:\n self._best_prediction = max(\n action_set.prediction\n for action_set in self._action_sets.values()\n )\n return self._best_prediction", "response": "The highest value from among the predictions made by the action\n sets in this match set."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef best_actions(self):\n if self._best_actions is None:\n best_prediction = self.best_prediction\n self._best_actions = tuple(\n action\n for action, action_set in self._action_sets.items()\n if action_set.prediction == best_prediction\n )\n return self._best_actions", "response": "A tuple containing the actions whose action sets have the best\n prediction."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef select_action(self):\n if self._selected_action is not None:\n raise ValueError(\"The action has already been selected.\")\n strategy = self._algorithm.action_selection_strategy\n self._selected_action = strategy(self)\n return self._selected_action", "response": "Select an action according to the action selection strategy of the associated algorithm."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _set_selected_action(self, action):\n assert action in self._action_sets\n\n if self._selected_action is not None:\n raise ValueError(\"The action has already been selected.\")\n self._selected_action = action", "response": "Setter method for the selected_action property."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _set_payoff(self, payoff):\n if self._selected_action is None:\n raise ValueError(\"The action has not been selected yet.\")\n if self._closed:\n raise ValueError(\"The payoff for this match set has already\"\n \"been applied.\")\n self._payoff = float(payoff)", "response": "Setter method for the payoff property."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef pay(self, predecessor):\n assert predecessor is None or isinstance(predecessor, MatchSet)\n\n if predecessor is not None:\n expectation = self._algorithm.get_future_expectation(self)\n predecessor.payoff += expectation", "response": "This method pays the amount of time until the predecessor has been fulfilled."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\napplying the payoff that has been accumulated from immediate reward and or payments from successor match sets.", "response": "def apply_payoff(self):\n \"\"\"Apply the payoff that has been accumulated from immediate\n reward and/or payments from successor match sets. Attempting to\n call this method before an action has been selected or after it\n has already been called for the same match set will result in a\n ValueError.\n\n Usage:\n match_set.select_action()\n match_set.payoff = reward\n match_set.apply_payoff()\n\n Arguments: None\n Return: None\n \"\"\"\n if self._selected_action is None:\n raise ValueError(\"The action has not been selected yet.\")\n if self._closed:\n raise ValueError(\"The payoff for this match set has already\"\n \"been applied.\")\n self._algorithm.distribute_payoff(self)\n self._payoff = 0\n self._algorithm.update(self)\n self._closed = True"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\naccept a situation and return a MatchSet containing the classifier rules whose conditions match the situation.", "response": "def match(self, situation):\n \"\"\"Accept a situation (input) and return a MatchSet containing the\n classifier rules whose conditions match the situation. If\n appropriate per the algorithm managing this classifier set, create\n new rules to ensure sufficient coverage of the possible actions.\n\n Usage:\n match_set = model.match(situation)\n\n Arguments:\n situation: The situation for which a match set is desired.\n Return:\n A MatchSet instance for the given situation, drawn from the\n classifier rules in this classifier set.\n \"\"\"\n\n # Find the conditions that match against the current situation, and\n # group them according to which action(s) they recommend.\n by_action = {}\n for condition, actions in self._population.items():\n if not condition(situation):\n continue\n\n for action, rule in actions.items():\n if action in by_action:\n by_action[action][condition] = rule\n else:\n by_action[action] = {condition: rule}\n\n # Construct the match set.\n match_set = MatchSet(self, situation, by_action)\n\n # If an insufficient number of actions are recommended, create some\n # new rules (condition/action pairs) until there are enough actions\n # being recommended.\n if self._algorithm.covering_is_required(match_set):\n # Ask the algorithm to provide a new classifier rule to add to\n # the population.\n rule = self._algorithm.cover(match_set)\n\n # Ensure that the condition provided by the algorithm does\n # indeed match the situation. If not, there is a bug in the\n # algorithm.\n assert rule.condition(situation)\n\n # Add the new classifier, getting back a list of the rule(s)\n # which had to be removed to make room for it.\n replaced = self.add(rule)\n\n # Remove the rules that were removed the population from the\n # action set, as well. Note that they may not appear in the\n # action set, in which case nothing is done.\n for replaced_rule in replaced:\n action = replaced_rule.action\n condition = replaced_rule.condition\n if action in by_action and condition in by_action[action]:\n del by_action[action][condition]\n if not by_action[action]:\n del by_action[action]\n\n # Add the new classifier to the action set. This is done after\n # the replaced rules are removed, just in case the algorithm\n # provided us with a rule that was already present and was\n # displaced.\n if rule.action not in by_action:\n by_action[rule.action] = {}\n by_action[rule.action][rule.condition] = rule\n\n # Reconstruct the match set with the modifications we just\n # made.\n match_set = MatchSet(self, situation, by_action)\n\n # Return the newly created match set.\n return match_set"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nadding a new rule to the classifier set.", "response": "def add(self, rule):\n \"\"\"Add a new classifier rule to the classifier set. Return a list\n containing zero or more rules that were deleted from the classifier\n by the algorithm in order to make room for the new rule. The rule\n argument should be a ClassifierRule instance. The behavior of this\n method depends on whether the rule already exists in the\n classifier set. When a rule is already present, the rule's\n numerosity is added to that of the version of the rule already\n present in the population. Otherwise, the new rule is captured.\n Note that this means that for rules already present in the\n classifier set, the metadata of the existing rule is not\n overwritten by that of the one passed in as an argument.\n\n Usage:\n displaced_rules = model.add(rule)\n\n Arguments:\n rule: A ClassifierRule instance which is to be added to this\n classifier set.\n Return:\n A possibly empty list of ClassifierRule instances which were\n removed altogether from the classifier set (as opposed to\n simply having their numerosities decremented) in order to make\n room for the newly added rule.\n \"\"\"\n\n assert isinstance(rule, ClassifierRule)\n\n condition = rule.condition\n action = rule.action\n\n # If the rule already exists in the population, then we virtually\n # add the rule by incrementing the existing rule's numerosity. This\n # prevents redundancy in the rule set. Otherwise we capture the\n # new rule.\n if condition not in self._population:\n self._population[condition] = {}\n\n if action in self._population[condition]:\n existing_rule = self._population[condition][action]\n existing_rule.numerosity += rule.numerosity\n else:\n self._population[condition][action] = rule\n\n # Any time we add a rule, we need to call this to keep the\n # population size under control.\n return self._algorithm.prune(self)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef discard(self, rule, count=1):\n assert isinstance(rule, ClassifierRule)\n assert isinstance(count, int) and count >= 0\n\n rule = self.get(rule)\n if rule is None:\n return False\n\n # Only actually remove the rule if its numerosity drops below 1.\n rule.numerosity -= count\n if rule.numerosity <= 0:\n # Ensure that if there is still a reference to this rule\n # elsewhere, its numerosity is still well-defined.\n rule.numerosity = 0\n\n del self._population[rule.condition][rule.action]\n if not self._population[rule.condition]:\n del self._population[rule.condition]\n return True\n\n return False", "response": "Removes one or more instances of a rule from the classifier set."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the existing version of the given rule.", "response": "def get(self, rule, default=None):\n \"\"\"Return the existing version of the given rule. If the rule is\n not present in the classifier set, return the default. If no\n default was given, use None. This is useful for eliminating\n duplicate copies of rules.\n\n Usage:\n unique_rule = model.get(possible_duplicate, possible_duplicate)\n\n Arguments:\n rule: The ClassifierRule instance which may be a duplicate of\n another already contained in the classifier set.\n default: The value returned if the rule is not a duplicate of\n another already contained in the classifier set.\n Return:\n If the rule is a duplicate of another already contained in the\n classifier set, the existing one is returned. Otherwise, the\n value of default is returned.\n \"\"\"\n assert isinstance(rule, ClassifierRule)\n\n if (rule.condition not in self._population or\n rule.action not in self._population[rule.condition]):\n return default\n return self._population[rule.condition][rule.action]"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nruns the algorithm utilizing the classifier set to choose the most appropriate action for each situation produced by the classifier set and then execute the selected action.", "response": "def run(self, scenario, learn=True):\n \"\"\"Run the algorithm, utilizing the classifier set to choose the\n most appropriate action for each situation produced by the\n scenario. If learn is True, improve the situation/action mapping to\n maximize reward. Otherwise, ignore any reward received.\n\n Usage:\n model.run(scenario, learn=True)\n\n Arguments:\n scenario: A Scenario instance which this classifier set is to\n interact with.\n learn: A bool indicating whether the classifier set should\n attempt to optimize its performance based on reward\n received for each action, as opposed to simply using what\n it has already learned from previous runs and ignoring\n reward received; default is True.\n Return: None\n \"\"\"\n\n assert isinstance(scenario, scenarios.Scenario)\n\n previous_match_set = None\n\n # Repeat until the scenario has run its course.\n while scenario.more():\n # Gather information about the current state of the\n # environment.\n situation = scenario.sense()\n\n # Determine which rules match the current situation.\n match_set = self.match(situation)\n\n # Select the best action for the current situation (or a random\n # one, if we are on an exploration step).\n match_set.select_action()\n\n # Perform the selected action\n # and find out what the received reward was.\n reward = scenario.execute(match_set.selected_action)\n\n # If the scenario is dynamic, don't immediately apply the\n # reward; instead, wait until the next iteration and factor in\n # not only the reward that was received on the previous step,\n # but the (discounted) reward that is expected going forward\n # given the resulting situation observed after the action was\n # taken. This is a classic feature of temporal difference (TD)\n # algorithms, which acts to stitch together a general picture\n # of the future expected reward without actually waiting the\n # full duration to find out what it will be.\n if learn:\n # Ensure we are not trying to learn in a non-learning\n # scenario.\n assert reward is not None\n\n if scenario.is_dynamic:\n if previous_match_set is not None:\n match_set.pay(previous_match_set)\n previous_match_set.apply_payoff()\n match_set.payoff = reward\n\n # Remember the current reward and match set for the\n # next iteration.\n previous_match_set = match_set\n else:\n match_set.payoff = reward\n match_set.apply_payoff()\n\n # This serves to tie off the final stitch. The last action taken\n # gets only the immediate reward; there is no future reward\n # expected.\n if learn and previous_match_set is not None:\n previous_match_set.apply_payoff()"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nlist configuration files detected and examined paths.", "response": "def ls(system, user, local, include_missing):\n \"\"\"List configuration files detected (and/or examined paths).\"\"\"\n\n # default action is to list *all* auto-detected files\n if not (system or user or local):\n system = user = local = True\n\n for path in get_configfile_paths(system=system, user=user, local=local,\n only_existing=not include_missing):\n click.echo(path)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ninspecting existing configuration file and profile.", "response": "def inspect(config_file, profile):\n \"\"\"Inspect existing configuration/profile.\"\"\"\n\n try:\n section = load_profile_from_files(\n [config_file] if config_file else None, profile)\n\n click.echo(\"Configuration file: {}\".format(config_file if config_file else \"auto-detected\"))\n click.echo(\"Profile: {}\".format(profile if profile else \"auto-detected\"))\n click.echo(\"---\")\n for key, val in section.items():\n click.echo(\"{} = {}\".format(key, val))\n\n except (ValueError, ConfigFileReadError, ConfigFileParseError) as e:\n click.echo(e)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create(config_file, profile):\n\n # determine the config file path\n if config_file:\n click.echo(\"Using configuration file: {}\".format(config_file))\n else:\n # path not given, try to detect; or use default, but allow user to override\n config_file = get_configfile_path()\n if config_file:\n click.echo(\"Found existing configuration file: {}\".format(config_file))\n else:\n config_file = get_default_configfile_path()\n click.echo(\"Configuration file not found; the default location is: {}\".format(config_file))\n config_file = default_text_input(\"Configuration file path\", config_file)\n config_file = os.path.expanduser(config_file)\n\n # create config_file path\n config_base = os.path.dirname(config_file)\n if config_base and not os.path.exists(config_base):\n if click.confirm(\"Configuration file path does not exist. Create it?\", abort=True):\n try:\n os.makedirs(config_base)\n except Exception as e:\n click.echo(\"Error creating configuration path: {}\".format(e))\n return 1\n\n # try loading existing config, or use defaults\n try:\n config = load_config_from_files([config_file])\n except:\n config = get_default_config()\n\n # determine profile\n if profile:\n click.echo(\"Using profile: {}\".format(profile))\n else:\n existing = config.sections()\n if existing:\n profiles = 'create new or choose from: {}'.format(', '.join(existing))\n default_profile = ''\n else:\n profiles = 'create new'\n default_profile = 'prod'\n profile = default_text_input(\"Profile (%s)\" % profiles, default_profile, optional=False)\n\n if not config.has_section(profile):\n config.add_section(profile)\n\n # fill out the profile variables\n variables = 'endpoint token client solver proxy'.split()\n prompts = ['API endpoint URL',\n 'Authentication token',\n 'Default client class (qpu or sw)',\n 'Default solver']\n for var, prompt in zip(variables, prompts):\n default_val = config.get(profile, var, fallback=None)\n val = default_text_input(prompt, default_val)\n if val:\n val = os.path.expandvars(val)\n if val != default_val:\n config.set(profile, var, val)\n\n try:\n with open(config_file, 'w') as fp:\n config.write(fp)\n except Exception as e:\n click.echo(\"Error writing to configuration file: {}\".format(e))\n return 2\n\n click.echo(\"Configuration saved.\")\n return 0", "response": "Create and or update cloud client configuration file."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _ping(config_file, profile, solver_def, request_timeout, polling_timeout, output):\n\n config = dict(config_file=config_file, profile=profile, solver=solver_def)\n if request_timeout is not None:\n config.update(request_timeout=request_timeout)\n if polling_timeout is not None:\n config.update(polling_timeout=polling_timeout)\n try:\n client = Client.from_config(**config)\n except Exception as e:\n raise CLIError(\"Invalid configuration: {}\".format(e), code=1)\n if config_file:\n output(\"Using configuration file: {config_file}\", config_file=config_file)\n if profile:\n output(\"Using profile: {profile}\", profile=profile)\n output(\"Using endpoint: {endpoint}\", endpoint=client.endpoint)\n\n t0 = timer()\n try:\n solver = client.get_solver()\n except SolverAuthenticationError:\n raise CLIError(\"Authentication error. Check credentials in your configuration file.\", 2)\n except SolverNotFoundError:\n raise CLIError(\"Solver not available.\", 6)\n except (InvalidAPIResponseError, UnsupportedSolverError):\n raise CLIError(\"Invalid or unexpected API response.\", 3)\n except RequestTimeout:\n raise CLIError(\"API connection timed out.\", 4)\n except requests.exceptions.SSLError as e:\n # we need to handle `ssl.SSLError` wrapped in several exceptions,\n # with differences between py2/3; greping the message is the easiest way\n if 'CERTIFICATE_VERIFY_FAILED' in str(e):\n raise CLIError(\n \"Certificate verification failed. Please check that your API endpoint \"\n \"is correct. If you are connecting to a private or third-party D-Wave \"\n \"system that uses self-signed certificate(s), please see \"\n \"https://support.dwavesys.com/hc/en-us/community/posts/360018930954.\", 5)\n raise CLIError(\"Unexpected SSL error while fetching solver: {!r}\".format(e), 5)\n except Exception as e:\n raise CLIError(\"Unexpected error while fetching solver: {!r}\".format(e), 5)\n\n t1 = timer()\n output(\"Using solver: {solver_id}\", solver_id=solver.id)\n\n try:\n future = solver.sample_ising({0: 1}, {})\n timing = future.timing\n except RequestTimeout:\n raise CLIError(\"API connection timed out.\", 8)\n except PollingTimeout:\n raise CLIError(\"Polling timeout exceeded.\", 9)\n except Exception as e:\n raise CLIError(\"Sampling error: {!r}\".format(e), 10)\n finally:\n output(\"Submitted problem ID: {problem_id}\", problem_id=future.id)\n\n t2 = timer()\n\n output(\"\\nWall clock time:\")\n output(\" * Solver definition fetch: {wallclock_solver_definition:.3f} ms\", wallclock_solver_definition=(t1-t0)*1000.0)\n output(\" * Problem submit and results fetch: {wallclock_sampling:.3f} ms\", wallclock_sampling=(t2-t1)*1000.0)\n output(\" * Total: {wallclock_total:.3f} ms\", wallclock_total=(t2-t0)*1000.0)\n if timing.items():\n output(\"\\nQPU timing:\")\n for component, duration in timing.items():\n output(\" * %(name)s = {%(name)s} us\" % {\"name\": component}, **{component: duration})\n else:\n output(\"\\nQPU timing data not available.\")", "response": "Ping the D - Wave API."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\npings the QPU by submitting a single - qubit problem.", "response": "def ping(config_file, profile, solver_def, json_output, request_timeout, polling_timeout):\n \"\"\"Ping the QPU by submitting a single-qubit problem.\"\"\"\n\n now = utcnow()\n info = dict(datetime=now.isoformat(), timestamp=datetime_to_timestamp(now), code=0)\n\n def output(fmt, **kwargs):\n info.update(kwargs)\n if not json_output:\n click.echo(fmt.format(**kwargs))\n\n def flush():\n if json_output:\n click.echo(json.dumps(info))\n\n try:\n _ping(config_file, profile, solver_def, request_timeout, polling_timeout, output)\n except CLIError as error:\n output(\"Error: {error} (code: {code})\", error=str(error), code=error.code)\n sys.exit(error.code)\n except Exception as error:\n output(\"Unhandled error: {error}\", error=str(error))\n sys.exit(127)\n finally:\n flush()"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting solver details. Unless solver name/id specified, fetch and display details for all online solvers available on the configured endpoint.", "response": "def solvers(config_file, profile, solver_def, list_solvers):\n \"\"\"Get solver details.\n\n Unless solver name/id specified, fetch and display details for\n all online solvers available on the configured endpoint.\n \"\"\"\n\n with Client.from_config(\n config_file=config_file, profile=profile, solver=solver_def) as client:\n\n try:\n solvers = client.get_solvers(**client.default_solver)\n except SolverNotFoundError:\n click.echo(\"Solver(s) {} not found.\".format(solver_def))\n return 1\n\n if list_solvers:\n for solver in solvers:\n click.echo(solver.id)\n return\n\n # ~YAML output\n for solver in solvers:\n click.echo(\"Solver: {}\".format(solver.id))\n click.echo(\" Parameters:\")\n for name, val in sorted(solver.parameters.items()):\n click.echo(\" {}: {}\".format(name, strtrunc(val) if val else '?'))\n solver.properties.pop('parameters', None)\n click.echo(\" Properties:\")\n for name, val in sorted(solver.properties.items()):\n click.echo(\" {}: {}\".format(name, strtrunc(val)))\n click.echo(\" Derived properties:\")\n for name in sorted(solver.derived_properties):\n click.echo(\" {}: {}\".format(name, strtrunc(getattr(solver, name))))\n click.echo()"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nsubmits Ising - formulated problem and return samples.", "response": "def sample(config_file, profile, solver_def, biases, couplings, random_problem,\n num_reads, verbose):\n \"\"\"Submit Ising-formulated problem and return samples.\"\"\"\n\n # TODO: de-dup wrt ping\n\n def echo(s, maxlen=100):\n click.echo(s if verbose else strtrunc(s, maxlen))\n\n try:\n client = Client.from_config(\n config_file=config_file, profile=profile, solver=solver_def)\n except Exception as e:\n click.echo(\"Invalid configuration: {}\".format(e))\n return 1\n if config_file:\n echo(\"Using configuration file: {}\".format(config_file))\n if profile:\n echo(\"Using profile: {}\".format(profile))\n echo(\"Using endpoint: {}\".format(client.endpoint))\n\n try:\n solver = client.get_solver()\n except SolverAuthenticationError:\n click.echo(\"Authentication error. Check credentials in your configuration file.\")\n return 1\n except (InvalidAPIResponseError, UnsupportedSolverError):\n click.echo(\"Invalid or unexpected API response.\")\n return 2\n except SolverNotFoundError:\n click.echo(\"Solver with the specified features does not exist.\")\n return 3\n\n echo(\"Using solver: {}\".format(solver.id))\n\n if random_problem:\n linear, quadratic = generate_random_ising_problem(solver)\n else:\n try:\n linear = ast.literal_eval(biases) if biases else []\n except Exception as e:\n click.echo(\"Invalid biases: {}\".format(e))\n try:\n quadratic = ast.literal_eval(couplings) if couplings else {}\n except Exception as e:\n click.echo(\"Invalid couplings: {}\".format(e))\n\n echo(\"Using qubit biases: {!r}\".format(linear))\n echo(\"Using qubit couplings: {!r}\".format(quadratic))\n echo(\"Number of samples: {}\".format(num_reads))\n\n try:\n result = solver.sample_ising(linear, quadratic, num_reads=num_reads).result()\n except Exception as e:\n click.echo(e)\n return 4\n\n if verbose:\n click.echo(\"Result: {!r}\".format(result))\n\n echo(\"Samples: {!r}\".format(result['samples']))\n echo(\"Occurrences: {!r}\".format(result['occurrences']))\n echo(\"Energies: {!r}\".format(result['energies']))"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef get_input_callback(samplerate, params, num_samples=256):\n amplitude = params['mod_amplitude']\n frequency = params['mod_frequency']\n\n def producer():\n \"\"\"Generate samples.\n\n Yields\n ------\n samples : ndarray\n A number of samples (`num_samples`) of the sine.\n \"\"\"\n start_time = 0\n while True:\n time = start_time + np.arange(num_samples) / samplerate\n start_time += num_samples / samplerate\n output = amplitude * np.cos(2 * np.pi * frequency * time)\n yield output\n\n return lambda p=producer(): next(p)", "response": "Returns a function that produces samples of a sine."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn a callback that can be used to play the next frame of the next frame of the next frame.", "response": "def get_playback_callback(resampler, samplerate, params):\n \"\"\"Return a sound playback callback.\n\n Parameters\n ----------\n resampler\n The resampler from which samples are read.\n samplerate : float\n The sample rate.\n params : dict\n Parameters for FM generation.\n \"\"\"\n\n def callback(outdata, frames, time, _):\n \"\"\"Playback callback.\n\n Read samples from the resampler and modulate them onto a carrier\n frequency.\n \"\"\"\n last_fmphase = getattr(callback, 'last_fmphase', 0)\n df = params['fm_gain'] * resampler.read(frames)\n df = np.pad(df, (0, frames - len(df)), mode='constant')\n t = time.outputBufferDacTime + np.arange(frames) / samplerate\n phase = 2 * np.pi * params['carrier_frequency'] * t\n fmphase = last_fmphase + 2 * np.pi * np.cumsum(df) / samplerate\n outdata[:, 0] = params['output_volume'] * np.cos(phase + fmphase)\n callback.last_fmphase = fmphase[-1]\n\n return callback"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef main(source_samplerate, target_samplerate, params, converter_type):\n from time import sleep\n\n ratio = target_samplerate / source_samplerate\n\n with sr.CallbackResampler(get_input_callback(source_samplerate, params),\n ratio, converter_type) as resampler, \\\n sd.OutputStream(channels=1, samplerate=target_samplerate,\n callback=get_playback_callback(\n resampler, target_samplerate, params)):\n print(\"Playing back... Ctrl+C to stop.\")\n try:\n while True:\n sleep(1)\n except KeyboardInterrupt:\n print(\"Aborting.\")", "response": "Setup the resampling and audio output callbacks and start playback."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the maximum number of reads for the given solver parameters.", "response": "def max_num_reads(self, **params):\n \"\"\"Returns the maximum number of reads for the given solver parameters.\n\n Args:\n **params:\n Parameters for the sampling method. Relevant to num_reads:\n\n - annealing_time\n - readout_thermalization\n - num_reads\n - programming_thermalization\n\n Returns:\n int: The maximum number of reads.\n\n \"\"\"\n # dev note: in the future it would be good to have a way of doing this\n # server-side, as we are duplicating logic here.\n\n properties = self.properties\n\n if self.software or not params:\n # software solvers don't use any of the above parameters\n return properties['num_reads_range'][1]\n\n # qpu\n\n _, duration = properties['problem_run_duration_range']\n\n annealing_time = params.get('annealing_time',\n properties['default_annealing_time'])\n\n readout_thermalization = params.get('readout_thermalization',\n properties['default_readout_thermalization'])\n\n programming_thermalization = params.get('programming_thermalization',\n properties['default_programming_thermalization'])\n\n return min(properties['num_reads_range'][1],\n int((duration - programming_thermalization)\n / (annealing_time + readout_thermalization)))"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef sample_ising(self, linear, quadratic, **params):\n # Our linear and quadratic objective terms are already separated in an\n # ising model so we can just directly call `_sample`.\n return self._sample('ising', linear, quadratic, params)", "response": "Sample from the specified Ising model."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef sample_qubo(self, qubo, **params):\n # In a QUBO the linear and quadratic terms in the objective are mixed into\n # a matrix. For the sake of encoding, we will separate them before calling `_sample`\n linear = {i1: v for (i1, i2), v in uniform_iterator(qubo) if i1 == i2}\n quadratic = {(i1, i2): v for (i1, i2), v in uniform_iterator(qubo) if i1 != i2}\n return self._sample('qubo', linear, quadratic, params)", "response": "Sample from the specified binary contains an unconstrained binary entry."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _sample(self, type_, linear, quadratic, params):\n # Check the problem\n if not self.check_problem(linear, quadratic):\n raise ValueError(\"Problem graph incompatible with solver.\")\n\n # Mix the new parameters with the default parameters\n combined_params = dict(self._params)\n combined_params.update(params)\n\n # Check the parameters before submitting\n for key in combined_params:\n if key not in self.parameters and not key.startswith('x_'):\n raise KeyError(\"{} is not a parameter of this solver.\".format(key))\n\n # transform some of the parameters in-place\n self._format_params(type_, combined_params)\n\n body = json.dumps({\n 'solver': self.id,\n 'data': encode_bqm_as_qp(self, linear, quadratic),\n 'type': type_,\n 'params': combined_params\n })\n _LOGGER.trace(\"Encoded sample request: %s\", body)\n\n future = Future(solver=self, id_=None, return_matrix=self.return_matrix,\n submission_data=(type_, linear, quadratic, params))\n\n _LOGGER.debug(\"Submitting new problem to: %s\", self.id)\n self.client._submit(body, future)\n return future", "response": "Internal method for both sample_ising and sample_qubo."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _format_params(self, type_, params):\n if 'initial_state' in params:\n # NB: at this moment the error raised when initial_state does not match lin/quad (in\n # active qubits) is not very informative, but there is also no clean way to check here\n # that they match because lin can be either a list or a dict. In the future it would be\n # good to check.\n initial_state = params['initial_state']\n if isinstance(initial_state, Mapping):\n\n initial_state_list = [3]*self.properties['num_qubits']\n\n low = -1 if type_ == 'ising' else 0\n\n for v, val in initial_state.items():\n if val == 3:\n continue\n if val <= 0:\n initial_state_list[v] = low\n else:\n initial_state_list[v] = 1\n\n params['initial_state'] = initial_state_list", "response": "Reformat some of the parameters for sapi."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef check_problem(self, linear, quadratic):\n for key, value in uniform_iterator(linear):\n if value != 0 and key not in self.nodes:\n return False\n for key, value in uniform_iterator(quadratic):\n if value != 0 and tuple(key) not in self.edges:\n return False\n return True", "response": "Test if an Ising model matches the graph provided by the solver."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _retrieve_problem(self, id_):\n future = Future(self, id_, self.return_matrix, None)\n self.client._poll(future)\n return future", "response": "Resume polling for a problem previously submitted."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the converter type for identifier.", "response": "def _get_converter_type(identifier):\n \"\"\"Return the converter type for `identifier`.\"\"\"\n if isinstance(identifier, str):\n return ConverterType[identifier]\n if isinstance(identifier, ConverterType):\n return identifier\n return ConverterType(identifier)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef resample(input_data, ratio, converter_type='sinc_best', verbose=False):\n from samplerate.lowlevel import src_simple\n from samplerate.exceptions import ResamplingError\n\n input_data = np.require(input_data, requirements='C', dtype=np.float32)\n if input_data.ndim == 2:\n num_frames, channels = input_data.shape\n output_shape = (int(num_frames * ratio), channels)\n elif input_data.ndim == 1:\n num_frames, channels = input_data.size, 1\n output_shape = (int(num_frames * ratio), )\n else:\n raise ValueError('rank > 2 not supported')\n\n output_data = np.empty(output_shape, dtype=np.float32)\n converter_type = _get_converter_type(converter_type)\n\n (error, input_frames_used, output_frames_gen) \\\n = src_simple(input_data, output_data, ratio,\n converter_type.value, channels)\n\n if error != 0:\n raise ResamplingError(error)\n\n if verbose:\n info = ('samplerate info:\\n'\n '{} input frames used\\n'\n '{} output frames generated\\n'\n .format(input_frames_used, output_frames_gen))\n print(info)\n\n return (output_data[:output_frames_gen, :]\n if channels > 1 else output_data[:output_frames_gen])", "response": "Resample the signal in input_data at once."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef set_ratio(self, new_ratio):\n from samplerate.lowlevel import src_set_ratio\n return src_set_ratio(self._state, new_ratio)", "response": "Set a new conversion ratio immediately."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _create(self):\n from samplerate.lowlevel import ffi, src_callback_new, src_delete\n from samplerate.exceptions import ResamplingError\n\n state, handle, error = src_callback_new(\n self._callback, self._converter_type.value, self._channels)\n if error != 0:\n raise ResamplingError(error)\n self._state = ffi.gc(state, src_delete)\n self._handle = handle", "response": "Create new callback resampler."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef set_starting_ratio(self, ratio):\n from samplerate.lowlevel import src_set_ratio\n if self._state is None:\n self._create()\n src_set_ratio(self._state, ratio)\n self.ratio = ratio", "response": "Set the starting conversion ratio for the next read call."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nresets the state of the object.", "response": "def reset(self):\n \"\"\"Reset state.\"\"\"\n from samplerate.lowlevel import src_reset\n if self._state is None:\n self._create()\n src_reset(self._state)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nread a number of frames from the resampler.", "response": "def read(self, num_frames):\n \"\"\"Read a number of frames from the resampler.\n\n Parameters\n ----------\n num_frames : int\n Number of frames to read.\n\n Returns\n -------\n output_data : ndarray\n Resampled frames as a (`num_output_frames`, `num_channels`) or\n (`num_output_frames`,) array. Note that this may return fewer frames\n than requested, for example when no more input is available.\n \"\"\"\n from samplerate.lowlevel import src_callback_read, src_error\n from samplerate.exceptions import ResamplingError\n\n if self._state is None:\n self._create()\n if self._channels > 1:\n output_shape = (num_frames, self._channels)\n elif self._channels == 1:\n output_shape = (num_frames, )\n output_data = np.empty(output_shape, dtype=np.float32)\n\n ret = src_callback_read(self._state, self._ratio, num_frames,\n output_data)\n if ret == 0:\n error = src_error(self._state)\n if error:\n raise ResamplingError(error)\n\n return (output_data[:ret, :]\n if self._channels > 1 else output_data[:ret])"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_variance(seq):\n m = get_mean(seq)\n return sum((v-m)**2 for v in seq)/float(len(seq))", "response": "Calculate the batch variance of a sequence."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef mean_absolute_error(seq, correct):\n assert len(seq) == len(correct)\n diffs = [abs(a-b) for a, b in zip(seq, correct)]\n return sum(diffs)/float(len(diffs))", "response": "Calculate the mean absolute error of a sequence."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef normalize(seq):\n s = float(sum(seq))\n return [v/s for v in seq]", "response": "Normalizes each number in the sequence so that the sum of all numbers equals 1."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns the probability that a real - valued random variable X is found at a value less than or equal to mu and sigma.", "response": "def normcdf(x, mu, sigma):\n \"\"\"\n Describes the probability that a real-valued random variable X with a given\n probability distribution will be found at a value less than or equal to X\n in a normal distribution.\n \n http://en.wikipedia.org/wiki/Cumulative_distribution_function\n \"\"\"\n t = x-mu\n y = 0.5*erfcc(-t/(sigma*math.sqrt(2.0)))\n if y > 1.0:\n y = 1.0\n return y"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef normpdf(x, mu, sigma):\n u = (x-mu)/abs(sigma)\n y = (1/(math.sqrt(2*pi)*abs(sigma)))*math.exp(-u*u/2)\n return y", "response": "Returns the relative likelihood that a real - valued random variable X will\n take on a given value."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncalculate the entropy of the attribute attr in given data set.", "response": "def entropy(data, class_attr=None, method=DEFAULT_DISCRETE_METRIC):\n \"\"\"\n Calculates the entropy of the attribute attr in given data set data.\n \n Parameters:\n data