SBML L{}V{}\".format(model.getId(),\n model.getLevel(), model.getVersion())\n packages = {}\n for k in range(doc.getNumPlugins()):\n plugin = doc.getPlugin(k) # type:libsbml.SBasePlugin\n key, value = plugin.getPackageName(), plugin.getPackageVersion()\n packages[key] = value\n info += \", {}-v{}\".format(key, value)\n if key not in [\"fbc\", \"groups\"]:\n LOGGER.warning(\"SBML package '%s' not supported by cobrapy,\"\n \"information is not parsed\", key)\n meta[\"info\"] = info\n meta[\"packages\"] = packages\n cobra_model._sbml = meta\n\n # notes and annotations\n cobra_model.notes = _parse_notes_dict(model)\n cobra_model.annotation = _parse_annotations(model)\n\n # Compartments\n # FIXME: update with new compartments\n cobra_model.compartments = {c.getId(): c.getName()\n for c in model.getListOfCompartments()}\n\n # Species\n metabolites = []\n boundary_metabolites = []\n if model.getNumSpecies() == 0:\n LOGGER.warning(\"No metabolites in model\")\n\n for specie in model.getListOfSpecies(): # type: libsbml.Species\n sid = _check_required(specie, specie.getId(), \"id\")\n if f_replace and F_SPECIE in f_replace:\n sid = f_replace[F_SPECIE](sid)\n\n met = Metabolite(sid)\n met.name = specie.getName()\n met.notes = _parse_notes_dict(specie)\n met.annotation = _parse_annotations(specie)\n met.compartment = specie.getCompartment()\n\n specie_fbc = specie.getPlugin(\"fbc\") # type: libsbml.FbcSpeciesPlugin\n if specie_fbc:\n met.charge = specie_fbc.getCharge()\n met.formula = specie_fbc.getChemicalFormula()\n else:\n if specie.isSetCharge():\n LOGGER.warning(\"Use of the species charge attribute is \"\n \"discouraged, use fbc:charge \"\n \"instead: %s\", specie)\n met.charge = specie.getCharge()\n else:\n if 'CHARGE' in met.notes:\n LOGGER.warning(\"Use of CHARGE in the notes element is \"\n \"discouraged, use fbc:charge \"\n \"instead: %s\", specie)\n try:\n met.charge = int(met.notes['CHARGE'])\n except ValueError:\n # handle nan, na, NA, ...\n pass\n\n if 'FORMULA' in met.notes:\n LOGGER.warning(\"Use of FORMULA in the notes element is \"\n \"discouraged, use fbc:chemicalFormula \"\n \"instead: %s\", specie)\n met.formula = met.notes['FORMULA']\n\n # Detect boundary metabolites\n if specie.getBoundaryCondition() is True:\n boundary_metabolites.append(met)\n\n metabolites.append(met)\n\n cobra_model.add_metabolites(metabolites)\n\n # Add exchange reactions for boundary metabolites\n ex_reactions = []\n for met in boundary_metabolites:\n ex_rid = \"EX_{}\".format(met.id)\n ex_reaction = Reaction(ex_rid)\n ex_reaction.name = ex_rid\n ex_reaction.annotation = {\n 'sbo': SBO_EXCHANGE_REACTION\n }\n ex_reaction.lower_bound = -float(\"Inf\")\n ex_reaction.upper_bound = float(\"Inf\")\n LOGGER.warning(\"Adding exchange reaction %s for boundary metabolite: \"\n \"%s\" % (ex_reaction.id, met.id))\n # species is reactant\n ex_reaction.add_metabolites({met: -1})\n ex_reactions.append(ex_reaction)\n cobra_model.add_reactions(ex_reactions)\n\n # Genes\n if model_fbc:\n for gp in model_fbc.getListOfGeneProducts(): # noqa: E501 type: libsbml.GeneProduct\n gid = gp.getId()\n if f_replace and F_GENE in f_replace:\n gid = f_replace[F_GENE](gid)\n cobra_gene = Gene(gid)\n cobra_gene.name = gp.getName()\n if cobra_gene.name is None:\n cobra_gene.name = gid\n cobra_gene.annotation = _parse_annotations(gp)\n cobra_gene.notes = _parse_notes_dict(gp)\n\n cobra_model.genes.append(cobra_gene)\n else:\n for cobra_reaction in model.getListOfReactions(): # noqa: E501 type: libsbml.Reaction\n # fallback to notes information\n notes = _parse_notes_dict(cobra_reaction)\n if \"GENE ASSOCIATION\" in notes:\n gpr = notes['GENE ASSOCIATION']\n elif \"GENE_ASSOCIATION\" in notes:\n gpr = notes['GENE_ASSOCIATION']\n else:\n gpr = ''\n\n if len(gpr) > 0:\n gpr = gpr.replace(\"(\", \";\")\n gpr = gpr.replace(\")\", \";\")\n gpr = gpr.replace(\"or\", \";\")\n gpr = gpr.replace(\"and\", \";\")\n gids = [t.strip() for t in gpr.split(';')]\n\n # create missing genes\n for gid in gids:\n if f_replace and F_GENE in f_replace:\n gid = f_replace[F_GENE](gid)\n\n if gid not in cobra_model.genes:\n cobra_gene = Gene(gid)\n cobra_gene.name = gid\n cobra_model.genes.append(cobra_gene)\n\n # GPR rules\n def process_association(ass):\n \"\"\" Recursively convert gpr association to a gpr string.\n Defined as inline functions to not pass the replacement dict around.\n \"\"\"\n if ass.isFbcOr():\n return \" \".join(\n [\"(\", ' or '.join(process_association(c)\n for c in ass.getListOfAssociations()), \")\"]\n )\n elif ass.isFbcAnd():\n return \" \".join(\n [\"(\", ' and '.join(process_association(c)\n for c in ass.getListOfAssociations()), \")\"])\n elif ass.isGeneProductRef():\n gid = ass.getGeneProduct()\n if f_replace and F_GENE in f_replace:\n return f_replace[F_GENE](gid)\n else:\n return gid\n\n # Reactions\n missing_bounds = False\n reactions = []\n if model.getNumReactions() == 0:\n LOGGER.warning(\"No reactions in model\")\n\n for reaction in model.getListOfReactions(): # type: libsbml.Reaction\n rid = _check_required(reaction, reaction.getId(), \"id\")\n if f_replace and F_REACTION in f_replace:\n rid = f_replace[F_REACTION](rid)\n cobra_reaction = Reaction(rid)\n cobra_reaction.name = reaction.getName()\n cobra_reaction.annotation = _parse_annotations(reaction)\n cobra_reaction.notes = _parse_notes_dict(reaction)\n\n # set bounds\n p_ub, p_lb = None, None\n r_fbc = reaction.getPlugin(\"fbc\") # type: libsbml.FbcReactionPlugin\n if r_fbc:\n # bounds in fbc\n lb_id = r_fbc.getLowerFluxBound()\n if lb_id:\n p_lb = model.getParameter(lb_id) # type: libsbml.Parameter\n if p_lb and p_lb.getConstant() and \\\n (p_lb.getValue() is not None):\n cobra_reaction.lower_bound = p_lb.getValue()\n else:\n raise CobraSBMLError(\"No constant bound '%s' for \"\n \"reaction: %s\" % (p_lb, reaction))\n\n ub_id = r_fbc.getUpperFluxBound()\n if ub_id:\n p_ub = model.getParameter(ub_id) # type: libsbml.Parameter\n if p_ub and p_ub.getConstant() and \\\n (p_ub.getValue() is not None):\n cobra_reaction.upper_bound = p_ub.getValue()\n else:\n raise CobraSBMLError(\"No constant bound '%s' for \"\n \"reaction: %s\" % (p_ub, reaction))\n\n elif reaction.isSetKineticLaw():\n # some legacy models encode bounds in kinetic laws\n klaw = reaction.getKineticLaw() # type: libsbml.KineticLaw\n p_lb = klaw.getParameter(\"LOWER_BOUND\") # noqa: E501 type: libsbml.LocalParameter\n if p_lb:\n cobra_reaction.lower_bound = p_lb.getValue()\n p_ub = klaw.getParameter(\"UPPER_BOUND\") # noqa: E501 type: libsbml.LocalParameter\n if p_ub:\n cobra_reaction.upper_bound = p_ub.getValue()\n\n if p_ub is not None or p_lb is not None:\n LOGGER.warning(\"Encoding LOWER_BOUND and UPPER_BOUND in \"\n \"KineticLaw is discouraged, \"\n \"use fbc:fluxBounds instead: %s\", reaction)\n\n if p_lb is None:\n missing_bounds = True\n if set_missing_bounds:\n lower_bound = config.lower_bound\n else:\n lower_bound = -float(\"Inf\")\n cobra_reaction.lower_bound = lower_bound\n LOGGER.warning(\"Missing lower flux bound set to '%s' for \"\n \" reaction: '%s'\", lower_bound, reaction)\n\n if p_ub is None:\n missing_bounds = True\n if set_missing_bounds:\n upper_bound = config.upper_bound\n else:\n upper_bound = float(\"Inf\")\n cobra_reaction.upper_bound = upper_bound\n LOGGER.warning(\"Missing upper flux bound set to '%s' for \"\n \" reaction: '%s'\", upper_bound, reaction)\n\n # add reaction\n reactions.append(cobra_reaction)\n\n # parse equation\n stoichiometry = defaultdict(lambda: 0)\n for sref in reaction.getListOfReactants(): # noqa: E501 type: libsbml.SpeciesReference\n sid = sref.getSpecies()\n if f_replace and F_SPECIE in f_replace:\n sid = f_replace[F_SPECIE](sid)\n stoichiometry[sid] -= number(\n _check_required(sref, sref.getStoichiometry(),\n \"stoichiometry\"))\n\n for sref in reaction.getListOfProducts(): # noqa: E501 type: libsbml.SpeciesReference\n sid = sref.getSpecies()\n if f_replace and F_SPECIE in f_replace:\n sid = f_replace[F_SPECIE](sid)\n stoichiometry[sid] += number(\n _check_required(sref, sref.getStoichiometry(),\n \"stoichiometry\"))\n\n # convert to metabolite objects\n object_stoichiometry = {}\n for met_id in stoichiometry:\n metabolite = cobra_model.metabolites.get_by_id(met_id)\n object_stoichiometry[metabolite] = stoichiometry[met_id]\n cobra_reaction.add_metabolites(object_stoichiometry)\n\n # GPR\n if r_fbc:\n gpr = ''\n gpa = r_fbc.getGeneProductAssociation() # noqa: E501 type: libsbml.GeneProductAssociation\n if gpa is not None:\n association = gpa.getAssociation() # noqa: E501 type: libsbml.FbcAssociation\n gpr = process_association(association)\n else:\n # fallback to notes information\n notes = cobra_reaction.notes\n if \"GENE ASSOCIATION\" in notes:\n gpr = notes['GENE ASSOCIATION']\n elif \"GENE_ASSOCIATION\" in notes:\n gpr = notes['GENE_ASSOCIATION']\n else:\n gpr = ''\n\n if len(gpr) > 0:\n LOGGER.warning(\"Use of GENE ASSOCIATION or GENE_ASSOCIATION \"\n \"in the notes element is discouraged, use \"\n \"fbc:gpr instead: %s\", reaction)\n if f_replace and F_GENE in f_replace:\n gpr = \" \".join(\n f_replace[F_GENE](t) for t in gpr.split(' ')\n )\n\n # remove outside parenthesis, if any\n if gpr.startswith(\"(\") and gpr.endswith(\")\"):\n gpr = gpr[1:-1].strip()\n\n cobra_reaction.gene_reaction_rule = gpr\n\n cobra_model.add_reactions(reactions)\n\n # Objective\n obj_direction = \"max\"\n coefficients = {}\n if model_fbc:\n obj_list = model_fbc.getListOfObjectives() # noqa: E501 type: libsbml.ListOfObjectives\n if obj_list is None:\n LOGGER.warning(\"listOfObjectives element not found\")\n elif obj_list.size() == 0:\n LOGGER.warning(\"No objective in listOfObjectives\")\n elif not obj_list.getActiveObjective():\n LOGGER.warning(\"No active objective in listOfObjectives\")\n else:\n obj_id = obj_list.getActiveObjective()\n obj = model_fbc.getObjective(obj_id) # type: libsbml.Objective\n obj_direction = LONG_SHORT_DIRECTION[obj.getType()]\n\n for flux_obj in obj.getListOfFluxObjectives(): # noqa: E501 type: libsbml.FluxObjective\n rid = flux_obj.getReaction()\n if f_replace and F_REACTION in f_replace:\n rid = f_replace[F_REACTION](rid)\n try:\n objective_reaction = cobra_model.reactions.get_by_id(rid)\n except KeyError:\n raise CobraSBMLError(\"Objective reaction '%s' \"\n \"not found\" % rid)\n try:\n coefficients[objective_reaction] = number(\n flux_obj.getCoefficient()\n )\n except ValueError as e:\n LOGGER.warning(str(e))\n else:\n # some legacy models encode objective coefficients in kinetic laws\n for reaction in model.getListOfReactions(): # noqa: E501 type: libsbml.Reaction\n if reaction.isSetKineticLaw():\n klaw = reaction.getKineticLaw() # type: libsbml.KineticLaw\n p_oc = klaw.getParameter(\n \"OBJECTIVE_COEFFICIENT\") # noqa: E501 type: libsbml.LocalParameter\n if p_oc:\n rid = reaction.getId()\n if f_replace and F_REACTION in f_replace:\n rid = f_replace[F_REACTION](rid)\n try:\n objective_reaction = cobra_model.reactions.get_by_id(\n rid)\n except KeyError:\n raise CobraSBMLError(\"Objective reaction '%s' \"\n \"not found\", rid)\n try:\n coefficients[objective_reaction] = number(\n p_oc.getValue())\n except ValueError as e:\n LOGGER.warning(str(e))\n\n LOGGER.warning(\"Encoding OBJECTIVE_COEFFICIENT in \"\n \"KineticLaw is discouraged, \"\n \"use fbc:fluxObjective \"\n \"instead: %s\", cobra_reaction)\n\n if len(coefficients) == 0:\n LOGGER.error(\"No objective coefficients in model. Unclear what should \"\n \"be optimized\")\n set_objective(cobra_model, coefficients)\n cobra_model.solver.objective.direction = obj_direction\n\n # parse groups\n model_groups = model.getPlugin(\"groups\") # type: libsbml.GroupsModelPlugin\n groups = []\n if model_groups:\n # calculate hashmaps to lookup objects in O(1)\n sid_map = {}\n metaid_map = {}\n for obj_list in [model.getListOfCompartments(),\n model.getListOfSpecies(),\n model.getListOfReactions(),\n model_groups.getListOfGroups()]:\n\n for sbase in obj_list: # type: libsbml.SBase\n if sbase.isSetId():\n sid_map[sbase.getId()] = sbase\n if sbase.isSetMetaId():\n metaid_map[sbase.getMetaId()] = sbase\n\n # create groups\n for group in model_groups.getListOfGroups(): # type: libsbml.Group\n cobra_group = Group(group.getId())\n cobra_group.name = group.getName()\n if group.isSetKind():\n cobra_group.kind = group.getKindAsString()\n cobra_group.annotation = _parse_annotations(group)\n cobra_group.notes = _parse_notes_dict(group)\n\n cobra_members = []\n for member in group.getListOfMembers(): # type: libsbml.Member\n if member.isSetIdRef():\n obj = sid_map[member.getIdRef()]\n # obj = doc.getElementBySId(member.getIdRef())\n elif member.isSetMetaIdRef():\n obj = metaid_map[member.getMetaIdRef()]\n # obj = doc.getElementByMetaId(member.getMetaIdRef())\n\n typecode = obj.getTypeCode()\n obj_id = obj.getId()\n\n # id replacements\n cobra_member = None\n if typecode == libsbml.SBML_SPECIES:\n if f_replace and F_SPECIE in f_replace:\n obj_id = f_replace[F_SPECIE](obj_id)\n cobra_member = cobra_model.metabolites.get_by_id(obj_id)\n elif typecode == libsbml.SBML_REACTION:\n if f_replace and F_REACTION in f_replace:\n obj_id = f_replace[F_REACTION](obj_id)\n cobra_member = cobra_model.reactions.get_by_id(obj_id)\n elif typecode == libsbml.SBML_FBC_GENEPRODUCT:\n if f_replace and F_GENE in f_replace:\n obj_id = f_replace[F_GENE](obj_id)\n cobra_member = cobra_model.genes.get_by_id(obj_id)\n else:\n LOGGER.warning(\"Member %s could not be added to group %s.\"\n \"unsupported type code: \"\n \"%s\" % (member, group, typecode))\n\n if cobra_member:\n cobra_members.append(cobra_member)\n\n cobra_group.add_members(cobra_members)\n groups.append(cobra_group)\n else:\n # parse deprecated subsystems on reactions\n groups_dict = {}\n for cobra_reaction in cobra_model.reactions:\n if \"SUBSYSTEM\" in cobra_reaction.notes:\n g_name = cobra_reaction.notes[\"SUBSYSTEM\"]\n if g_name in groups_dict:\n groups_dict[g_name].append(cobra_reaction)\n else:\n groups_dict[g_name] = [cobra_reaction]\n\n for gid, cobra_members in groups_dict.items():\n cobra_group = Group(gid, name=gid, kind=\"collection\")\n cobra_group.add_members(cobra_members)\n groups.append(cobra_group)\n\n cobra_model.add_groups(groups)\n\n # general hint for missing flux bounds\n if missing_bounds and not set_missing_bounds:\n LOGGER.warning(\"Missing flux bounds on reactions. As best practise \"\n \"and to avoid confusion flux bounds should be set \"\n \"explicitly on all reactions. \"\n \"To set the missing flux bounds to default bounds \"\n \"specified in cobra.Configuration use the flag \"\n \"`read_sbml_model(..., set_missing_bounds=True)`.\")\n\n return cobra_model"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef write_sbml_model(cobra_model, filename, f_replace=F_REPLACE, **kwargs):\n doc = _model_to_sbml(cobra_model, f_replace=f_replace, **kwargs)\n\n if isinstance(filename, string_types):\n # write to path\n libsbml.writeSBMLToFile(doc, filename)\n\n elif hasattr(filename, \"write\"):\n # write to file handle\n sbml_str = libsbml.writeSBMLToString(doc)\n filename.write(sbml_str)", "response": "Writes a SBML model to a file."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _model_to_sbml(cobra_model, f_replace=None, units=True):\n if f_replace is None:\n f_replace = {}\n\n sbml_ns = libsbml.SBMLNamespaces(3, 1) # SBML L3V1\n sbml_ns.addPackageNamespace(\"fbc\", 2) # fbc-v2\n\n doc = libsbml.SBMLDocument(sbml_ns) # noqa: E501 type: libsbml.SBMLDocument\n doc.setPackageRequired(\"fbc\", False)\n doc.setSBOTerm(SBO_FBA_FRAMEWORK)\n\n model = doc.createModel() # type: libsbml.Model\n model_fbc = model.getPlugin(\"fbc\") # type: libsbml.FbcModelPlugin\n model_fbc.setStrict(True)\n\n if cobra_model.id is not None:\n model.setId(cobra_model.id)\n model.setMetaId(\"meta_\" + cobra_model.id)\n else:\n model.setMetaId(\"meta_model\")\n if cobra_model.name is not None:\n model.setName(cobra_model.name)\n\n _sbase_annotations(model, cobra_model.annotation)\n\n # Meta information (ModelHistory)\n if hasattr(cobra_model, \"_sbml\"):\n meta = cobra_model._sbml\n if \"annotation\" in meta:\n _sbase_annotations(doc, meta[\"annotation\"])\n if \"notes\" in meta:\n _sbase_notes_dict(doc, meta[\"notes\"])\n\n history = libsbml.ModelHistory() # type: libsbml.ModelHistory\n if \"created\" in meta and meta[\"created\"]:\n history.setCreatedDate(meta[\"created\"])\n else:\n time = datetime.datetime.now()\n timestr = time.strftime('%Y-%m-%dT%H:%M:%S')\n date = libsbml.Date(timestr)\n _check(history.setCreatedDate(date), 'set creation date')\n _check(history.setModifiedDate(date), 'set modified date')\n\n if \"creators\" in meta:\n for cobra_creator in meta[\"creators\"]:\n creator = libsbml.ModelCreator() # noqa: E501 type: libsbml.ModelCreator\n if cobra_creator.get(\"familyName\", None):\n creator.setFamilyName(cobra_creator[\"familyName\"])\n if cobra_creator.get(\"givenName\", None):\n creator.setGivenName(cobra_creator[\"givenName\"])\n if cobra_creator.get(\"organisation\", None):\n creator.setOrganisation(cobra_creator[\"organisation\"])\n if cobra_creator.get(\"email\", None):\n creator.setEmail(cobra_creator[\"email\"])\n\n _check(history.addCreator(creator),\n \"adding creator to ModelHistory.\")\n _check(model.setModelHistory(history), 'set model history')\n\n # Units\n if units:\n flux_udef = model.createUnitDefinition() # noqa: E501 type: libsbml.UnitDefinition\n flux_udef.setId(UNITS_FLUX[0])\n for u in UNITS_FLUX[1]:\n unit = flux_udef.createUnit() # type: libsbml.Unit\n unit.setKind(u.kind)\n unit.setExponent(u.exponent)\n unit.setScale(u.scale)\n unit.setMultiplier(u.multiplier)\n\n # minimum and maximum value from model\n if len(cobra_model.reactions) > 0:\n min_value = min(cobra_model.reactions.list_attr(\"lower_bound\"))\n max_value = max(cobra_model.reactions.list_attr(\"upper_bound\"))\n else:\n min_value = config.lower_bound\n max_value = config.upper_bound\n\n _create_parameter(model, pid=LOWER_BOUND_ID,\n value=min_value, sbo=SBO_DEFAULT_FLUX_BOUND)\n _create_parameter(model, pid=UPPER_BOUND_ID,\n value=max_value, sbo=SBO_DEFAULT_FLUX_BOUND)\n _create_parameter(model, pid=ZERO_BOUND_ID,\n value=0, sbo=SBO_DEFAULT_FLUX_BOUND)\n _create_parameter(model, pid=BOUND_MINUS_INF,\n value=-float(\"Inf\"), sbo=SBO_FLUX_BOUND)\n _create_parameter(model, pid=BOUND_PLUS_INF,\n value=float(\"Inf\"), sbo=SBO_FLUX_BOUND)\n\n # Compartments\n # FIXME: use first class compartment model (and write notes & annotations)\n # (https://github.com/opencobra/cobrapy/issues/811)\n for cid, name in iteritems(cobra_model.compartments):\n compartment = model.createCompartment() # type: libsbml.Compartment\n compartment.setId(cid)\n compartment.setName(name)\n compartment.setConstant(True)\n\n # FIXME: write annotations and notes\n # _sbase_notes(c, com.notes)\n # _sbase_annotations(c, com.annotation)\n\n # Species\n for metabolite in cobra_model.metabolites:\n specie = model.createSpecies() # type: libsbml.Species\n mid = metabolite.id\n if f_replace and F_SPECIE_REV in f_replace:\n mid = f_replace[F_SPECIE_REV](mid)\n specie.setId(mid)\n specie.setConstant(False)\n specie.setBoundaryCondition(False)\n specie.setHasOnlySubstanceUnits(False)\n specie.setName(metabolite.name)\n specie.setCompartment(metabolite.compartment)\n s_fbc = specie.getPlugin(\"fbc\") # type: libsbml.FbcSpeciesPlugin\n if metabolite.charge is not None:\n s_fbc.setCharge(metabolite.charge)\n if metabolite.formula is not None:\n s_fbc.setChemicalFormula(metabolite.formula)\n\n _sbase_annotations(specie, metabolite.annotation)\n _sbase_notes_dict(specie, metabolite.notes)\n\n # Genes\n for cobra_gene in cobra_model.genes:\n gp = model_fbc.createGeneProduct() # type: libsbml.GeneProduct\n gid = cobra_gene.id\n if f_replace and F_GENE_REV in f_replace:\n gid = f_replace[F_GENE_REV](gid)\n gp.setId(gid)\n gname = cobra_gene.name\n if gname is None or len(gname) == 0:\n gname = gid\n gp.setName(gname)\n gp.setLabel(gid)\n\n _sbase_annotations(gp, cobra_gene.annotation)\n _sbase_notes_dict(gp, cobra_gene.notes)\n\n # Objective\n objective = model_fbc.createObjective() # type: libsbml.Objective\n objective.setId(\"obj\")\n objective.setType(SHORT_LONG_DIRECTION[cobra_model.objective.direction])\n model_fbc.setActiveObjectiveId(\"obj\")\n\n # Reactions\n reaction_coefficients = linear_reaction_coefficients(cobra_model)\n for cobra_reaction in cobra_model.reactions:\n rid = cobra_reaction.id\n if f_replace and F_REACTION_REV in f_replace:\n rid = f_replace[F_REACTION_REV](rid)\n reaction = model.createReaction() # type: libsbml.Reaction\n reaction.setId(rid)\n reaction.setName(cobra_reaction.name)\n reaction.setFast(False)\n reaction.setReversible((cobra_reaction.lower_bound < 0))\n _sbase_annotations(reaction, cobra_reaction.annotation)\n _sbase_notes_dict(reaction, cobra_reaction.notes)\n\n # stoichiometry\n for metabolite, stoichiometry in iteritems(cobra_reaction._metabolites): # noqa: E501\n sid = metabolite.id\n if f_replace and F_SPECIE_REV in f_replace:\n sid = f_replace[F_SPECIE_REV](sid)\n if stoichiometry < 0:\n sref = reaction.createReactant() # noqa: E501 type: libsbml.SpeciesReference\n sref.setSpecies(sid)\n sref.setStoichiometry(-stoichiometry)\n sref.setConstant(True)\n else:\n sref = reaction.createProduct() # noqa: E501 type: libsbml.SpeciesReference\n sref.setSpecies(sid)\n sref.setStoichiometry(stoichiometry)\n sref.setConstant(True)\n\n # bounds\n r_fbc = reaction.getPlugin(\"fbc\") # type: libsbml.FbcReactionPlugin\n r_fbc.setLowerFluxBound(_create_bound(model, cobra_reaction,\n \"lower_bound\",\n f_replace=f_replace, units=units,\n flux_udef=flux_udef))\n r_fbc.setUpperFluxBound(_create_bound(model, cobra_reaction,\n \"upper_bound\",\n f_replace=f_replace, units=units,\n flux_udef=flux_udef))\n\n # GPR\n gpr = cobra_reaction.gene_reaction_rule\n if gpr is not None and len(gpr) > 0:\n\n # replace ids in string\n if f_replace and F_GENE_REV in f_replace:\n gpr = gpr.replace('(', '( ')\n gpr = gpr.replace(')', ' )')\n tokens = gpr.split(' ')\n for k in range(len(tokens)):\n if tokens[k] not in [' ', 'and', 'or', '(', ')']:\n tokens[k] = f_replace[F_GENE_REV](tokens[k])\n gpr_new = \" \".join(tokens)\n\n gpa = r_fbc.createGeneProductAssociation() # noqa: E501 type: libsbml.GeneProductAssociation\n gpa.setAssociation(gpr_new)\n\n # objective coefficients\n if reaction_coefficients.get(cobra_reaction, 0) != 0:\n flux_obj = objective.createFluxObjective() # noqa: E501 type: libsbml.FluxObjective\n flux_obj.setReaction(rid)\n flux_obj.setCoefficient(cobra_reaction.objective_coefficient)\n\n # write groups\n if len(cobra_model.groups) > 0:\n doc.enablePackage(\n \"http://www.sbml.org/sbml/level3/version1/groups/version1\",\n \"groups\", True)\n doc.setPackageRequired(\"groups\", False)\n model_group = model.getPlugin(\"groups\") # noqa: E501 type: libsbml.GroupsModelPlugin\n for cobra_group in cobra_model.groups:\n group = model_group.createGroup() # type: libsbml.Group\n group.setId(cobra_group.id)\n group.setName(cobra_group.name)\n group.setKind(cobra_group.kind)\n\n _sbase_notes_dict(group, cobra_group.notes)\n _sbase_annotations(group, cobra_group.annotation)\n\n for cobra_member in cobra_group.members:\n member = group.createMember() # type: libsbml.Member\n mid = cobra_member.id\n m_type = str(type(cobra_member))\n\n # id replacements\n if \"Reaction\" in m_type:\n if f_replace and F_REACTION_REV in f_replace:\n mid = f_replace[F_REACTION_REV](mid)\n if \"Metabolite\" in m_type:\n if f_replace and F_SPECIE_REV in f_replace:\n mid = f_replace[F_SPECIE_REV](mid)\n if \"Gene\" in m_type:\n if f_replace and F_GENE_REV in f_replace:\n mid = f_replace[F_GENE_REV](mid)\n\n member.setIdRef(mid)\n if cobra_member.name and len(cobra_member.name) > 0:\n member.setName(cobra_member.name)\n\n return doc", "response": "Convert a Cobra model to SBMLDocument."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _create_bound(model, reaction, bound_type, f_replace, units=None,\n flux_udef=None):\n \"\"\"Creates bound in model for given reaction.\n\n Adds the parameters for the bounds to the SBML model.\n\n Parameters\n ----------\n model : libsbml.Model\n SBML model instance\n reaction : cobra.core.Reaction\n Cobra reaction instance from which the bounds are read.\n bound_type : {LOWER_BOUND, UPPER_BOUND}\n Type of bound\n f_replace : dict of id replacement functions\n units : flux units\n\n Returns\n -------\n Id of bound parameter.\n \"\"\"\n value = getattr(reaction, bound_type)\n if value == config.lower_bound:\n return LOWER_BOUND_ID\n elif value == 0:\n return ZERO_BOUND_ID\n elif value == config.upper_bound:\n return UPPER_BOUND_ID\n elif value == -float(\"Inf\"):\n return BOUND_MINUS_INF\n elif value == float(\"Inf\"):\n return BOUND_PLUS_INF\n else:\n # new parameter\n rid = reaction.id\n if f_replace and F_REACTION_REV in f_replace:\n rid = f_replace[F_REACTION_REV](rid)\n pid = rid + \"_\" + bound_type\n _create_parameter(model, pid=pid, value=value, sbo=SBO_FLUX_BOUND,\n units=units, flux_udef=flux_udef)\n return pid", "response": "Creates bound in model for given reaction."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _create_parameter(model, pid, value, sbo=None, constant=True, units=None,\n flux_udef=None):\n \"\"\"Create parameter in SBML model.\"\"\"\n parameter = model.createParameter() # type: libsbml.Parameter\n parameter.setId(pid)\n parameter.setValue(value)\n parameter.setConstant(constant)\n if sbo:\n parameter.setSBOTerm(sbo)\n if units:\n parameter.setUnits(flux_udef.getId())", "response": "Create parameter in SBML model."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nchecks if required attribute is set in SBase.", "response": "def _check_required(sbase, value, attribute):\n \"\"\"Get required attribute from SBase.\n\n Parameters\n ----------\n sbase : libsbml.SBase\n value : existing value\n attribute: name of attribute\n\n Returns\n -------\n attribute value (or value if already set)\n \"\"\"\n\n if (value is None) or (value == \"\"):\n msg = \"Required attribute '%s' cannot be found or parsed in '%s'\" % \\\n (attribute, sbase)\n if hasattr(sbase, \"getId\") and sbase.getId():\n msg += \" with id '%s'\" % sbase.getId()\n elif hasattr(sbase, \"getName\") and sbase.getName():\n msg += \" with name '%s'\" % sbase.getName()\n elif hasattr(sbase, \"getMetaId\") and sbase.getMetaId():\n msg += \" with metaId '%s'\" % sbase.getName()\n raise CobraSBMLError(msg)\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _check(value, message):\n if value is None:\n LOGGER.error('Error: LibSBML returned a null value trying '\n 'to <' + message + '>.')\n elif type(value) is int:\n if value == libsbml.LIBSBML_OPERATION_SUCCESS:\n return\n else:\n LOGGER.error('Error encountered trying to <' + message + '>.')\n LOGGER.error('LibSBML error code {}: {}'.format(str(value),\n libsbml.OperationReturnValue_toString(value).strip()))\n else:\n return", "response": "Checks the libsbml return value and logs error messages."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _parse_notes_dict(sbase):\n notes = sbase.getNotesString()\n if notes and len(notes) > 0:\n pattern = r\"\\s*(\\w+\\s*\\w*)\\s*:\\s*([\\w|\\s]+)<\"\n matches = re.findall(pattern, notes)\n d = {k.strip(): v.strip() for (k, v) in matches}\n return {k: v for k, v in d.items() if len(v) > 0}\n else:\n return {}", "response": "Creates dictionary of COBRA notes.\n\n Parameters\n ----------\n sbase : libsbml.SBase\n\n Returns\n -------\n dict of notes"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _sbase_notes_dict(sbase, notes):\n if notes and len(notes) > 0:\n tokens = [''] + \\\n [\"
{}: {}
\".format(k, v) for (k, v) in notes.items()] + \\\n [\"\"]\n _check(\n sbase.setNotes(\"\\n\".join(tokens)),\n \"Setting notes on sbase: {}\".format(sbase)\n )", "response": "Set SBase notes based on dictionary."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nparsing cobra annotations from a given SBase object.", "response": "def _parse_annotations(sbase):\n \"\"\"Parses cobra annotations from a given SBase object.\n\n Annotations are dictionaries with the providers as keys.\n\n Parameters\n ----------\n sbase : libsbml.SBase\n SBase from which the SBML annotations are read\n\n Returns\n -------\n dict (annotation dictionary)\n\n FIXME: annotation format must be updated (this is a big collection of\n fixes) - see: https://github.com/opencobra/cobrapy/issues/684)\n \"\"\"\n annotation = {}\n\n # SBO term\n if sbase.isSetSBOTerm():\n # FIXME: correct handling of annotations\n annotation[\"sbo\"] = sbase.getSBOTermID()\n\n # RDF annotation\n cvterms = sbase.getCVTerms()\n if cvterms is None:\n return annotation\n\n for cvterm in cvterms: # type: libsbml.CVTerm\n for k in range(cvterm.getNumResources()):\n # FIXME: read and store the qualifier\n\n uri = cvterm.getResourceURI(k)\n match = URL_IDENTIFIERS_PATTERN.match(uri)\n if not match:\n LOGGER.warning(\"%s does not conform to \"\n \"http(s)://identifiers.org/collection/id\", uri)\n continue\n\n provider, identifier = match.group(1), match.group(2)\n if provider in annotation:\n if isinstance(annotation[provider], string_types):\n annotation[provider] = [annotation[provider]]\n # FIXME: use a list\n if identifier not in annotation[provider]:\n annotation[provider].append(identifier)\n else:\n # FIXME: always in list\n annotation[provider] = identifier\n\n return annotation"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nsets SBase annotations based on cobra annotations.", "response": "def _sbase_annotations(sbase, annotation):\n \"\"\"Set SBase annotations based on cobra annotations.\n\n Parameters\n ----------\n sbase : libsbml.SBase\n SBML object to annotate\n annotation : cobra annotation structure\n cobra object with annotation information\n\n FIXME: annotation format must be updated\n (https://github.com/opencobra/cobrapy/issues/684)\n \"\"\"\n\n if not annotation or len(annotation) == 0:\n return\n\n # standardize annotations\n annotation_data = deepcopy(annotation)\n\n for key, value in annotation_data.items():\n # handling of non-string annotations (e.g. integers)\n if isinstance(value, (float, int)):\n value = str(value)\n if isinstance(value, string_types):\n annotation_data[key] = [(\"is\", value)]\n\n for key, value in annotation_data.items():\n for idx, item in enumerate(value):\n if isinstance(item, string_types):\n value[idx] = (\"is\", item)\n\n # set metaId\n meta_id = \"meta_{}\".format(sbase.getId())\n sbase.setMetaId(meta_id)\n\n # rdf_items = []\n for provider, data in iteritems(annotation_data):\n\n # set SBOTerm\n if provider in [\"SBO\", \"sbo\"]:\n if provider == \"SBO\":\n LOGGER.warning(\"'SBO' provider is deprecated, \"\n \"use 'sbo' provider instead\")\n sbo_term = data[0][1]\n _check(sbase.setSBOTerm(sbo_term),\n \"Setting SBOTerm: {}\".format(sbo_term))\n\n # FIXME: sbo should also be written as CVTerm\n continue\n\n for item in data:\n qualifier_str, entity = item[0], item[1]\n qualifier = QUALIFIER_TYPES.get(qualifier_str, None)\n if qualifier is None:\n qualifier = libsbml.BQB_IS\n LOGGER.error(\"Qualifier type is not supported on \"\n \"annotation: '{}'\".format(qualifier_str))\n\n qualifier_type = libsbml.BIOLOGICAL_QUALIFIER\n if qualifier_str.startswith(\"bqm_\"):\n qualifier_type = libsbml.MODEL_QUALIFIER\n\n cv = libsbml.CVTerm() # type: libsbml.CVTerm\n cv.setQualifierType(qualifier_type)\n if qualifier_type == libsbml.BIOLOGICAL_QUALIFIER:\n cv.setBiologicalQualifierType(qualifier)\n elif qualifier_type == libsbml.MODEL_QUALIFIER:\n cv.setModelQualifierType(qualifier)\n else:\n raise CobraSBMLError('Unsupported qualifier: '\n '%s' % qualifier)\n resource = \"%s/%s/%s\" % (URL_IDENTIFIERS_PREFIX, provider, entity)\n cv.addResource(resource)\n _check(sbase.addCVTerm(cv),\n \"Setting cvterm: {}, resource: {}\".format(cv, resource))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef validate_sbml_model(filename,\n check_model=True,\n internal_consistency=True,\n check_units_consistency=False,\n check_modeling_practice=False, **kwargs):\n \"\"\"Validate SBML model and returns the model along with a list of errors.\n\n Parameters\n ----------\n filename : str\n The filename (or SBML string) of the SBML model to be validated.\n internal_consistency: boolean {True, False}\n Check internal consistency.\n check_units_consistency: boolean {True, False}\n Check consistency of units.\n check_modeling_practice: boolean {True, False}\n Check modeling practise.\n check_model: boolean {True, False}\n Whether to also check some basic model properties such as reaction\n boundaries and compartment formulas.\n\n Returns\n -------\n (model, errors)\n model : :class:`~cobra.core.Model.Model` object\n The cobra model if the file could be read successfully or None\n otherwise.\n errors : dict\n Warnings and errors grouped by their respective types.\n\n Raises\n ------\n CobraSBMLError\n \"\"\"\n # Errors and warnings are grouped based on their type. SBML_* types are\n # from the libsbml validator. COBRA_* types are from the cobrapy SBML\n # parser.\n keys = (\n \"SBML_FATAL\",\n \"SBML_ERROR\",\n \"SBML_SCHEMA_ERROR\",\n \"SBML_WARNING\",\n\n \"COBRA_FATAL\",\n \"COBRA_ERROR\",\n \"COBRA_WARNING\",\n \"COBRA_CHECK\",\n )\n errors = {key: [] for key in keys}\n\n # [1] libsbml validation\n doc = _get_doc_from_filename(filename) # type: libsbml.SBMLDocument\n\n # set checking of units & modeling practise\n doc.setConsistencyChecks(libsbml.LIBSBML_CAT_UNITS_CONSISTENCY,\n check_units_consistency)\n doc.setConsistencyChecks(libsbml.LIBSBML_CAT_MODELING_PRACTICE,\n check_modeling_practice)\n\n # check internal consistency\n if internal_consistency:\n doc.checkInternalConsistency()\n doc.checkConsistency()\n\n for k in range(doc.getNumErrors()):\n e = doc.getError(k) # type: libsbml.SBMLError\n msg = _error_string(e, k=k)\n sev = e.getSeverity()\n if sev == libsbml.LIBSBML_SEV_FATAL:\n errors[\"SBML_FATAL\"].append(msg)\n elif sev == libsbml.LIBSBML_SEV_ERROR:\n errors[\"SBML_ERROR\"].append(msg)\n elif sev == libsbml.LIBSBML_SEV_SCHEMA_ERROR:\n errors[\"SBML_SCHEMA_ERROR\"].append(msg)\n elif sev == libsbml.LIBSBML_SEV_WARNING:\n errors[\"SBML_WARNING\"].append(msg)\n\n # [2] cobrapy validation (check that SBML can be read into model)\n # all warnings generated while loading will be logged as errors\n log_stream = StringIO()\n stream_handler = logging.StreamHandler(log_stream)\n formatter = logging.Formatter('%(levelname)s:%(message)s')\n stream_handler.setFormatter(formatter)\n stream_handler.setLevel(logging.INFO)\n LOGGER.addHandler(stream_handler)\n LOGGER.propagate = False\n\n try:\n # read model and allow additional parser arguments\n model = _sbml_to_model(doc, **kwargs)\n except CobraSBMLError as e:\n errors[\"COBRA_ERROR\"].append(str(e))\n return None, errors\n except Exception as e:\n errors[\"COBRA_FATAL\"].append(str(e))\n return None, errors\n\n cobra_errors = log_stream.getvalue().split(\"\\n\")\n for cobra_error in cobra_errors:\n tokens = cobra_error.split(\":\")\n error_type = tokens[0]\n error_msg = \":\".join(tokens[1:])\n\n if error_type == \"WARNING\":\n errors[\"COBRA_WARNING\"].append(error_msg)\n elif error_type == \"ERROR\":\n errors[\"COBRA_ERROR\"].append(error_msg)\n\n # remove stream handler\n LOGGER.removeHandler(stream_handler)\n LOGGER.propagate = True\n\n # [3] additional model tests\n if check_model:\n errors[\"COBRA_CHECK\"].extend(\n check_metabolite_compartment_formula(model)\n )\n\n for key in [\"SBML_FATAL\", \"SBML_ERROR\", \"SBML_SCHEMA_ERROR\"]:\n if len(errors[key]) > 0:\n LOGGER.error(\"SBML errors in validation, check error log \"\n \"for details.\")\n break\n for key in [\"SBML_WARNING\"]:\n if len(errors[key]) > 0:\n LOGGER.error(\"SBML warnings in validation, check error log \"\n \"for details.\")\n break\n for key in [\"COBRA_FATAL\", \"COBRA_ERROR\"]:\n if len(errors[key]) > 0:\n LOGGER.error(\"COBRA errors in validation, check error log \"\n \"for details.\")\n break\n for key in [\"COBRA_WARNING\", \"COBRA_CHECK\"]:\n if len(errors[key]) > 0:\n LOGGER.error(\"COBRA warnings in validation, check error log \"\n \"for details.\")\n break\n\n return model, errors", "response": "Validate the SBML file and return the model and errors."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _error_string(error, k=None):\n package = error.getPackage()\n if package == '':\n package = 'core'\n\n template = 'E{} ({}): {} ({}, L{}); {}; {}'\n error_str = template.format(k, error.getSeverityAsString(),\n error.getCategoryAsString(), package,\n error.getLine(), error.getShortMessage(),\n error.getMessage())\n return error_str", "response": "Returns a string representation of an error."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef production_envelope(model, reactions, objective=None, carbon_sources=None,\n points=20, threshold=None):\n \"\"\"Calculate the objective value conditioned on all combinations of\n fluxes for a set of chosen reactions\n\n The production envelope can be used to analyze a model's ability to\n produce a given compound conditional on the fluxes for another set of\n reactions, such as the uptake rates. The model is alternately optimized\n with respect to minimizing and maximizing the objective and the\n obtained fluxes are recorded. Ranges to compute production is set to the\n effective\n bounds, i.e., the minimum / maximum fluxes that can be obtained given\n current reaction bounds.\n\n Parameters\n ----------\n model : cobra.Model\n The model to compute the production envelope for.\n reactions : list or string\n A list of reactions, reaction identifiers or a single reaction.\n objective : string, dict, model.solver.interface.Objective, optional\n The objective (reaction) to use for the production envelope. Use the\n model's current objective if left missing.\n carbon_sources : list or string, optional\n One or more reactions or reaction identifiers that are the source of\n carbon for computing carbon (mol carbon in output over mol carbon in\n input) and mass yield (gram product over gram output). Only objectives\n with a carbon containing input and output metabolite is supported.\n Will identify active carbon sources in the medium if none are specified.\n points : int, optional\n The number of points to calculate production for.\n threshold : float, optional\n A cut-off under which flux values will be considered to be zero\n (default model.tolerance).\n\n Returns\n -------\n pandas.DataFrame\n A data frame with one row per evaluated point and\n\n - reaction id : one column per input reaction indicating the flux at\n each given point,\n - carbon_source: identifiers of carbon exchange reactions\n\n A column for the maximum and minimum each for the following types:\n\n - flux: the objective flux\n - carbon_yield: if carbon source is defined and the product is a\n single metabolite (mol carbon product per mol carbon feeding source)\n - mass_yield: if carbon source is defined and the product is a\n single metabolite (gram product per 1 g of feeding source)\n\n Examples\n --------\n >>> import cobra.test\n >>> from cobra.flux_analysis import production_envelope\n >>> model = cobra.test.create_test_model(\"textbook\")\n >>> production_envelope(model, [\"EX_glc__D_e\", \"EX_o2_e\"])\n\n \"\"\"\n\n reactions = model.reactions.get_by_any(reactions)\n objective = model.solver.objective if objective is None else objective\n data = dict()\n\n if carbon_sources is None:\n c_input = find_carbon_sources(model)\n else:\n c_input = model.reactions.get_by_any(carbon_sources)\n\n if c_input is None:\n data['carbon_source'] = None\n elif hasattr(c_input, 'id'):\n data['carbon_source'] = c_input.id\n else:\n data['carbon_source'] = ', '.join(rxn.id for rxn in c_input)\n\n threshold = normalize_cutoff(model, threshold)\n\n size = points ** len(reactions)\n\n for direction in ('minimum', 'maximum'):\n data['flux_{}'.format(direction)] = full(size, nan, dtype=float)\n data['carbon_yield_{}'.format(direction)] = full(\n size, nan, dtype=float)\n data['mass_yield_{}'.format(direction)] = full(\n size, nan, dtype=float)\n\n grid = pd.DataFrame(data)\n\n with model:\n model.objective = objective\n objective_reactions = list(sutil.linear_reaction_coefficients(model))\n\n if len(objective_reactions) != 1:\n raise ValueError('cannot calculate yields for objectives with '\n 'multiple reactions')\n c_output = objective_reactions[0]\n min_max = fva(model, reactions, fraction_of_optimum=0)\n min_max[min_max.abs() < threshold] = 0.0\n points = list(product(*[\n linspace(min_max.at[rxn.id, \"minimum\"],\n min_max.at[rxn.id, \"maximum\"],\n points, endpoint=True) for rxn in reactions]))\n tmp = pd.DataFrame(points, columns=[rxn.id for rxn in reactions])\n grid = pd.concat([grid, tmp], axis=1, copy=False)\n add_envelope(model, reactions, grid, c_input, c_output, threshold)\n\n return grid", "response": "Calculates the production envelope for a given set of reactions and model."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef total_yield(input_fluxes, input_elements, output_flux, output_elements):\n\n carbon_input_flux = sum(\n total_components_flux(flux, components, consumption=True)\n for flux, components in zip(input_fluxes, input_elements))\n carbon_output_flux = total_components_flux(\n output_flux, output_elements, consumption=False)\n try:\n return carbon_output_flux / carbon_input_flux\n except ZeroDivisionError:\n return nan", "response": "Compute total output per input unit."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef reaction_elements(reaction):\n c_elements = [coeff * met.elements.get('C', 0)\n for met, coeff in iteritems(reaction.metabolites)]\n return [elem for elem in c_elements if elem != 0]", "response": "Returns a list of all the metabolites that are desired in the reaction."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the metabolite weight times its stoichiometric coefficient.", "response": "def reaction_weight(reaction):\n \"\"\"Return the metabolite weight times its stoichiometric coefficient.\"\"\"\n\n if len(reaction.metabolites) != 1:\n raise ValueError('Reaction weight is only defined for single '\n 'metabolite products or educts.')\n\n met, coeff = next(iteritems(reaction.metabolites))\n\n return [coeff * met.formula_weight]"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ncomputing the total components consumption or production flux.", "response": "def total_components_flux(flux, components, consumption=True):\n \"\"\"\n Compute the total components consumption or production flux.\n\n Parameters\n ----------\n flux : float\n The reaction flux for the components.\n components : list\n List of stoichiometrically weighted components.\n consumption : bool, optional\n Whether to sum up consumption or production fluxes.\n\n \"\"\"\n\n direction = 1 if consumption else -1\n c_flux = [elem * flux * direction for elem in components]\n\n return sum([flux for flux in c_flux if flux > 0])"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nfinds all active carbon source reactions.", "response": "def find_carbon_sources(model):\n \"\"\"\n Find all active carbon source reactions.\n\n Parameters\n ----------\n model : Model\n A genome-scale metabolic model.\n\n Returns\n -------\n list\n The medium reactions with carbon input flux.\n\n \"\"\"\n\n try:\n model.slim_optimize(error_value=None)\n except OptimizationError:\n return []\n\n reactions = model.reactions.get_by_any(list(model.medium))\n reactions_fluxes = [\n (rxn, total_components_flux(rxn.flux, reaction_elements(rxn),\n consumption=True)) for rxn in reactions]\n return [rxn for rxn, c_flux in reactions_fluxes if c_flux > 0]"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nassess the production capacity of a given model.", "response": "def assess(model, reaction, flux_coefficient_cutoff=0.001, solver=None):\n \"\"\"Assesses production capacity.\n\n Assesses the capacity of the model to produce the precursors for the\n reaction and absorb the production of the reaction while the reaction is\n operating at, or above, the specified cutoff.\n\n Parameters\n ----------\n model : cobra.Model\n The cobra model to assess production capacity for\n\n reaction : reaction identifier or cobra.Reaction\n The reaction to assess\n\n flux_coefficient_cutoff : float\n The minimum flux that reaction must carry to be considered active.\n\n solver : basestring\n Solver name. If None, the default solver will be used.\n\n Returns\n -------\n bool or dict\n True if the model can produce the precursors and absorb the products\n for the reaction operating at, or above, flux_coefficient_cutoff.\n Otherwise, a dictionary of {'precursor': Status, 'product': Status}.\n Where Status is the results from assess_precursors and\n assess_products, respectively.\n\n \"\"\"\n reaction = model.reactions.get_by_any(reaction)[0]\n with model as m:\n m.objective = reaction\n if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:\n return True\n else:\n results = dict()\n results['precursors'] = assess_component(\n model, reaction, 'reactants', flux_coefficient_cutoff)\n results['products'] = assess_component(\n model, reaction, 'products', flux_coefficient_cutoff)\n return results"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef assess_component(model, reaction, side, flux_coefficient_cutoff=0.001,\n solver=None):\n \"\"\"Assesses the ability of the model to provide sufficient precursors,\n or absorb products, for a reaction operating at, or beyond,\n the specified cutoff.\n\n Parameters\n ----------\n model : cobra.Model\n The cobra model to assess production capacity for\n\n reaction : reaction identifier or cobra.Reaction\n The reaction to assess\n\n side : basestring\n Side of the reaction, 'products' or 'reactants'\n\n flux_coefficient_cutoff : float\n The minimum flux that reaction must carry to be considered active.\n\n solver : basestring\n Solver name. If None, the default solver will be used.\n\n Returns\n -------\n bool or dict\n True if the precursors can be simultaneously produced at the\n specified cutoff. False, if the model has the capacity to produce\n each individual precursor at the specified threshold but not all\n precursors at the required level simultaneously. Otherwise a\n dictionary of the required and the produced fluxes for each reactant\n that is not produced in sufficient quantities.\n\n \"\"\"\n reaction = model.reactions.get_by_any(reaction)[0]\n result_key = dict(reactants='produced', products='capacity')[side]\n get_components = attrgetter(side)\n with model as m:\n m.objective = reaction\n if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:\n return True\n simulation_results = {}\n # build the demand reactions and add all at once\n demand_reactions = {}\n for component in get_components(reaction):\n coeff = reaction.metabolites[component]\n demand = m.add_boundary(component, type='demand')\n demand.metabolites[component] = coeff\n demand_reactions[demand] = (component, coeff)\n # First assess whether all precursors can be produced simultaneously\n joint_demand = Reaction(\"joint_demand\")\n for demand_reaction in demand_reactions:\n joint_demand += demand_reaction\n m.add_reactions([joint_demand])\n m.objective = joint_demand\n if _optimize_or_value(m, solver=solver) >= flux_coefficient_cutoff:\n return True\n\n # Otherwise assess the ability of the model to produce each precursor\n # individually. Now assess the ability of the model to produce each\n # reactant for a reaction\n for demand_reaction, (component, coeff) in iteritems(demand_reactions):\n # Calculate the maximum amount of the\n with m:\n m.objective = demand_reaction\n flux = _optimize_or_value(m, solver=solver)\n # metabolite that can be produced.\n if flux_coefficient_cutoff > flux:\n # Scale the results to a single unit\n simulation_results.update({\n component: {\n 'required': flux_coefficient_cutoff / abs(coeff),\n result_key: flux / abs(coeff)\n }})\n if len(simulation_results) == 0:\n simulation_results = False\n return simulation_results", "response": "Assesses the ability of the model to provide sufficient precursors and absorb products for a given reaction."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nassesses the ability of the model to provide sufficient precursors for a given reaction.", "response": "def assess_precursors(model, reaction, flux_coefficient_cutoff=0.001,\n solver=None):\n \"\"\"Assesses the ability of the model to provide sufficient precursors for\n a reaction operating at, or beyond, the specified cutoff.\n\n Deprecated: use assess_component instead\n\n Parameters\n ----------\n model : cobra.Model\n The cobra model to assess production capacity for\n\n reaction : reaction identifier or cobra.Reaction\n The reaction to assess\n\n flux_coefficient_cutoff : float\n The minimum flux that reaction must carry to be considered active.\n\n solver : basestring\n Solver name. If None, the default solver will be used.\n\n Returns\n -------\n bool or dict\n True if the precursors can be simultaneously produced at the\n specified cutoff. False, if the model has the capacity to produce\n each individual precursor at the specified threshold but not all\n precursors at the required level simultaneously. Otherwise a\n dictionary of the required and the produced fluxes for each reactant\n that is not produced in sufficient quantities.\n\n \"\"\"\n warn('use assess_component instead', DeprecationWarning)\n return assess_component(model, reaction, 'reactants',\n flux_coefficient_cutoff, solver)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef assess_products(model, reaction, flux_coefficient_cutoff=0.001,\n solver=None):\n \"\"\"Assesses whether the model has the capacity to absorb the products of\n a reaction at a given flux rate.\n\n Useful for identifying which components might be blocking a reaction\n from achieving a specific flux rate.\n\n Deprecated: use assess_component instead\n\n Parameters\n ----------\n model : cobra.Model\n The cobra model to assess production capacity for\n\n reaction : reaction identifier or cobra.Reaction\n The reaction to assess\n\n flux_coefficient_cutoff : float\n The minimum flux that reaction must carry to be considered active.\n\n solver : basestring\n Solver name. If None, the default solver will be used.\n\n Returns\n -------\n bool or dict\n True if the model has the capacity to absorb all the reaction\n products being simultaneously given the specified cutoff. False,\n if the model has the capacity to absorb each individual product but\n not all products at the required level simultaneously. Otherwise a\n dictionary of the required and the capacity fluxes for each product\n that is not absorbed in sufficient quantities.\n\n \"\"\"\n warn('use assess_component instead', DeprecationWarning)\n return assess_component(model, reaction, 'products',\n flux_coefficient_cutoff, solver)", "response": "Assesses whether the model has the capacity to absorb the products of a given reaction at a given flux rate."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef add_loopless(model, zero_cutoff=None):\n zero_cutoff = normalize_cutoff(model, zero_cutoff)\n\n internal = [i for i, r in enumerate(model.reactions) if not r.boundary]\n s_int = create_stoichiometric_matrix(model)[:, numpy.array(internal)]\n n_int = nullspace(s_int).T\n max_bound = max(max(abs(b) for b in r.bounds) for r in model.reactions)\n prob = model.problem\n\n # Add indicator variables and new constraints\n to_add = []\n for i in internal:\n rxn = model.reactions[i]\n # indicator variable a_i\n indicator = prob.Variable(\"indicator_\" + rxn.id, type=\"binary\")\n # -M*(1 - a_i) <= v_i <= M*a_i\n on_off_constraint = prob.Constraint(\n rxn.flux_expression - max_bound * indicator,\n lb=-max_bound, ub=0, name=\"on_off_\" + rxn.id)\n # -(max_bound + 1) * a_i + 1 <= G_i <= -(max_bound + 1) * a_i + 1000\n delta_g = prob.Variable(\"delta_g_\" + rxn.id)\n delta_g_range = prob.Constraint(\n delta_g + (max_bound + 1) * indicator,\n lb=1, ub=max_bound, name=\"delta_g_range_\" + rxn.id)\n to_add.extend([indicator, on_off_constraint, delta_g, delta_g_range])\n\n model.add_cons_vars(to_add)\n\n # Add nullspace constraints for G_i\n for i, row in enumerate(n_int):\n name = \"nullspace_constraint_\" + str(i)\n nullspace_constraint = prob.Constraint(Zero, lb=0, ub=0, name=name)\n model.add_cons_vars([nullspace_constraint])\n coefs = {model.variables[\n \"delta_g_\" + model.reactions[ridx].id]: row[i]\n for i, ridx in enumerate(internal) if\n abs(row[i]) > zero_cutoff}\n model.constraints[name].set_linear_coefficients(coefs)", "response": "Modify a model so all feasible flux distributions are loopless."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nadds constraints for CycleFreeFlux.", "response": "def _add_cycle_free(model, fluxes):\n \"\"\"Add constraints for CycleFreeFlux.\"\"\"\n model.objective = model.solver.interface.Objective(\n Zero, direction=\"min\", sloppy=True)\n objective_vars = []\n for rxn in model.reactions:\n flux = fluxes[rxn.id]\n if rxn.boundary:\n rxn.bounds = (flux, flux)\n continue\n if flux >= 0:\n rxn.bounds = max(0, rxn.lower_bound), max(flux, rxn.upper_bound)\n objective_vars.append(rxn.forward_variable)\n else:\n rxn.bounds = min(flux, rxn.lower_bound), min(0, rxn.upper_bound)\n objective_vars.append(rxn.reverse_variable)\n\n model.objective.set_linear_coefficients({v: 1.0 for v in objective_vars})"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nconverts an existing loopless solution to a loopless one.", "response": "def loopless_solution(model, fluxes=None):\n \"\"\"Convert an existing solution to a loopless one.\n\n Removes as many loops as possible (see Notes).\n Uses the method from CycleFreeFlux [1]_ and is much faster than\n `add_loopless` and should therefore be the preferred option to get loopless\n flux distributions.\n\n Parameters\n ----------\n model : cobra.Model\n The model to which to add the constraints.\n fluxes : dict\n A dictionary {rxn_id: flux} that assigns a flux to each reaction. If\n not None will use the provided flux values to obtain a close loopless\n solution.\n\n Returns\n -------\n cobra.Solution\n A solution object containing the fluxes with the least amount of\n loops possible or None if the optimization failed (usually happening\n if the flux distribution in `fluxes` is infeasible).\n\n Notes\n -----\n The returned flux solution has the following properties:\n\n - it contains the minimal number of loops possible and no loops at all if\n all flux bounds include zero\n - it has an objective value close to the original one and the same\n objective value id the objective expression can not form a cycle\n (which is usually true since it consumes metabolites)\n - it has the same exact exchange fluxes as the previous solution\n - all fluxes have the same sign (flow in the same direction) as the\n previous solution\n\n References\n ----------\n .. [1] CycleFreeFlux: efficient removal of thermodynamically infeasible\n loops from flux distributions. Desouki AA, Jarre F, Gelius-Dietrich\n G, Lercher MJ. Bioinformatics. 2015 Jul 1;31(13):2159-65. doi:\n 10.1093/bioinformatics/btv096.\n \"\"\"\n # Need to reoptimize otherwise spurious solution artifacts can cause\n # all kinds of havoc\n # TODO: check solution status\n if fluxes is None:\n sol = model.optimize(objective_sense=None)\n fluxes = sol.fluxes\n\n with model:\n prob = model.problem\n # Needs one fixed bound for cplex...\n loopless_obj_constraint = prob.Constraint(\n model.objective.expression,\n lb=-1e32, name=\"loopless_obj_constraint\")\n model.add_cons_vars([loopless_obj_constraint])\n _add_cycle_free(model, fluxes)\n solution = model.optimize(objective_sense=None)\n solution.objective_value = loopless_obj_constraint.primal\n\n return solution"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncreating a stoichiometric matrix representation of the given model.", "response": "def create_stoichiometric_matrix(model, array_type='dense', dtype=None):\n \"\"\"Return a stoichiometric array representation of the given model.\n\n The the columns represent the reactions and rows represent\n metabolites. S[i,j] therefore contains the quantity of metabolite `i`\n produced (negative for consumed) by reaction `j`.\n\n Parameters\n ----------\n model : cobra.Model\n The cobra model to construct the matrix for.\n array_type : string\n The type of array to construct. if 'dense', return a standard\n numpy.array, 'dok', or 'lil' will construct a sparse array using\n scipy of the corresponding type and 'DataFrame' will give a\n pandas `DataFrame` with metabolite indices and reaction columns\n dtype : data-type\n The desired data-type for the array. If not given, defaults to float.\n\n Returns\n -------\n matrix of class `dtype`\n The stoichiometric matrix for the given model.\n \"\"\"\n if array_type not in ('DataFrame', 'dense') and not dok_matrix:\n raise ValueError('Sparse matrices require scipy')\n\n if dtype is None:\n dtype = np.float64\n\n array_constructor = {\n 'dense': np.zeros, 'dok': dok_matrix, 'lil': lil_matrix,\n 'DataFrame': np.zeros,\n }\n\n n_metabolites = len(model.metabolites)\n n_reactions = len(model.reactions)\n array = array_constructor[array_type]((n_metabolites, n_reactions),\n dtype=dtype)\n\n m_ind = model.metabolites.index\n r_ind = model.reactions.index\n\n for reaction in model.reactions:\n for metabolite, stoich in iteritems(reaction.metabolites):\n array[m_ind(metabolite), r_ind(reaction)] = stoich\n\n if array_type == 'DataFrame':\n metabolite_ids = [met.id for met in model.metabolites]\n reaction_ids = [rxn.id for rxn in model.reactions]\n return pd.DataFrame(array, index=metabolite_ids, columns=reaction_ids)\n\n else:\n return array"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef nullspace(A, atol=1e-13, rtol=0):\n A = np.atleast_2d(A)\n u, s, vh = np.linalg.svd(A)\n tol = max(atol, rtol * s[0])\n nnz = (s >= tol).sum()\n ns = vh[nnz:].conj().T\n return ns", "response": "Compute an approximate basis for the nullspace of A."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef constraint_matrices(model, array_type='dense', include_vars=False,\n zero_tol=1e-6):\n \"\"\"Create a matrix representation of the problem.\n\n This is used for alternative solution approaches that do not use optlang.\n The function will construct the equality matrix, inequality matrix and\n bounds for the complete problem.\n\n Notes\n -----\n To accomodate non-zero equalities the problem will add the variable\n \"const_one\" which is a variable that equals one.\n\n Arguments\n ---------\n model : cobra.Model\n The model from which to obtain the LP problem.\n array_type : string\n The type of array to construct. if 'dense', return a standard\n numpy.array, 'dok', or 'lil' will construct a sparse array using\n scipy of the corresponding type and 'DataFrame' will give a\n pandas `DataFrame` with metabolite indices and reaction columns.\n zero_tol : float\n The zero tolerance used to judge whether two bounds are the same.\n\n Returns\n -------\n collections.namedtuple\n A named tuple consisting of 6 matrices and 2 vectors:\n - \"equalities\" is a matrix S such that S*vars = b. It includes a row\n for each constraint and one column for each variable.\n - \"b\" the right side of the equality equation such that S*vars = b.\n - \"inequalities\" is a matrix M such that lb <= M*vars <= ub.\n It contains a row for each inequality and as many columns as\n variables.\n - \"bounds\" is a compound matrix [lb ub] containing the lower and\n upper bounds for the inequality constraints in M.\n - \"variable_fixed\" is a boolean vector indicating whether the variable\n at that index is fixed (lower bound == upper_bound) and\n is thus bounded by an equality constraint.\n - \"variable_bounds\" is a compound matrix [lb ub] containing the\n lower and upper bounds for all variables.\n \"\"\"\n if array_type not in ('DataFrame', 'dense') and not dok_matrix:\n raise ValueError('Sparse matrices require scipy')\n\n array_builder = {\n 'dense': np.array, 'dok': dok_matrix, 'lil': lil_matrix,\n 'DataFrame': pd.DataFrame,\n }[array_type]\n\n Problem = namedtuple(\"Problem\",\n [\"equalities\", \"b\", \"inequalities\", \"bounds\",\n \"variable_fixed\", \"variable_bounds\"])\n equality_rows = []\n inequality_rows = []\n inequality_bounds = []\n b = []\n\n for const in model.constraints:\n lb = -np.inf if const.lb is None else const.lb\n ub = np.inf if const.ub is None else const.ub\n equality = (ub - lb) < zero_tol\n coefs = const.get_linear_coefficients(model.variables)\n coefs = [coefs[v] for v in model.variables]\n if equality:\n b.append(lb if abs(lb) > zero_tol else 0.0)\n equality_rows.append(coefs)\n else:\n inequality_rows.append(coefs)\n inequality_bounds.append([lb, ub])\n\n var_bounds = np.array([[v.lb, v.ub] for v in model.variables])\n fixed = var_bounds[:, 1] - var_bounds[:, 0] < zero_tol\n\n results = Problem(\n equalities=array_builder(equality_rows),\n b=np.array(b),\n inequalities=array_builder(inequality_rows),\n bounds=array_builder(inequality_bounds),\n variable_fixed=np.array(fixed),\n variable_bounds=array_builder(var_bounds))\n\n return results", "response": "Create a matrix representation of the problem."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ncompute a single solution based on regulatory on/off minimization (ROOM). Compute a new flux distribution that minimizes the number of active reactions needed to accommodate a previous reference solution. Regulatory on/off minimization (ROOM) is generally used to assess the impact of knock-outs. Thus the typical usage is to provide a wildtype flux distribution as reference and a model in knock-out state. Parameters ---------- model : cobra.Model The model state to compute a ROOM-based solution for. solution : cobra.Solution, optional A (wildtype) reference solution. linear : bool, optional Whether to use the linear ROOM formulation or not (default False). delta: float, optional The relative tolerance range (additive) (default 0.03). epsilon: float, optional The absolute tolerance range (multiplicative) (default 0.001). Returns ------- cobra.Solution A flux distribution with minimal active reaction changes compared to the reference. See Also -------- add_room : add ROOM constraints and objective", "response": "def room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03):\n \"\"\"\n Compute a single solution based on regulatory on/off minimization (ROOM).\n\n Compute a new flux distribution that minimizes the number of active\n reactions needed to accommodate a previous reference solution.\n Regulatory on/off minimization (ROOM) is generally used to assess the\n impact of knock-outs. Thus the typical usage is to provide a wildtype flux\n distribution as reference and a model in knock-out state.\n\n Parameters\n ----------\n model : cobra.Model\n The model state to compute a ROOM-based solution for.\n solution : cobra.Solution, optional\n A (wildtype) reference solution.\n linear : bool, optional\n Whether to use the linear ROOM formulation or not (default False).\n delta: float, optional\n The relative tolerance range (additive) (default 0.03).\n epsilon: float, optional\n The absolute tolerance range (multiplicative) (default 0.001).\n\n Returns\n -------\n cobra.Solution\n A flux distribution with minimal active reaction changes compared to\n the reference.\n\n See Also\n --------\n add_room : add ROOM constraints and objective\n\n \"\"\"\n with model:\n add_room(model=model, solution=solution, linear=linear, delta=delta,\n epsilon=epsilon)\n solution = model.optimize()\n return solution"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nsampling valid flux distributions from a cobra model.", "response": "def sample(model, n, method=\"optgp\", thinning=100, processes=1, seed=None):\n \"\"\"Sample valid flux distributions from a cobra model.\n\n The function samples valid flux distributions from a cobra model.\n Currently we support two methods:\n\n 1. 'optgp' (default) which uses the OptGPSampler that supports parallel\n sampling [1]_. Requires large numbers of samples to be performant\n (n < 1000). For smaller samples 'achr' might be better suited.\n\n or\n\n 2. 'achr' which uses artificial centering hit-and-run. This is a single\n process method with good convergence [2]_.\n\n Parameters\n ----------\n model : cobra.Model\n The model from which to sample flux distributions.\n n : int\n The number of samples to obtain. When using 'optgp' this must be a\n multiple of `processes`, otherwise a larger number of samples will be\n returned.\n method : str, optional\n The sampling algorithm to use.\n thinning : int, optional\n The thinning factor of the generated sampling chain. A thinning of 10\n means samples are returned every 10 steps. Defaults to 100 which in\n benchmarks gives approximately uncorrelated samples. If set to one\n will return all iterates.\n processes : int, optional\n Only used for 'optgp'. The number of processes used to generate\n samples.\n seed : int > 0, optional\n The random number seed to be used. Initialized to current time stamp\n if None.\n\n Returns\n -------\n pandas.DataFrame\n The generated flux samples. Each row corresponds to a sample of the\n fluxes and the columns are the reactions.\n\n Notes\n -----\n The samplers have a correction method to ensure equality feasibility for\n long-running chains, however this will only work for homogeneous models,\n meaning models with no non-zero fixed variables or constraints (\n right-hand side of the equalities are zero).\n\n References\n ----------\n .. [1] Megchelenbrink W, Huynen M, Marchiori E (2014)\n optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space\n of Genome-Scale Metabolic Networks.\n PLoS ONE 9(2): e86587.\n .. [2] Direction Choice for Accelerated Convergence in Hit-and-Run Sampling\n David E. Kaufman Robert L. Smith\n Operations Research 199846:1 , 84-95\n\n \"\"\"\n\n if method == \"optgp\":\n sampler = OptGPSampler(model, processes, thinning=thinning, seed=seed)\n elif method == \"achr\":\n sampler = ACHRSampler(model, thinning=thinning, seed=seed)\n else:\n raise ValueError(\"method must be 'optgp' or 'achr'!\")\n\n return pandas.DataFrame(columns=[rxn.id for rxn in model.reactions],\n data=sampler.sample(n))"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef sample(self, n, fluxes=True):\n\n samples = np.zeros((n, self.warmup.shape[1]))\n\n for i in range(1, self.thinning * n + 1):\n self.__single_iteration()\n\n if i % self.thinning == 0:\n samples[i//self.thinning - 1, ] = self.prev\n\n if fluxes:\n names = [r.id for r in self.model.reactions]\n\n return pandas.DataFrame(\n samples[:, self.fwd_idx] - samples[:, self.rev_idx],\n columns=names)\n else:\n names = [v.name for v in self.model.variables]\n\n return pandas.DataFrame(samples, columns=names)", "response": "This function generates a set of samples for all hit - and - run samplers."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ngoogle Analytics tracking template tag. Renders Javascript code to track page visits. You must supply your website property ID (as a string) in the ``GOOGLE_ANALYTICS_PROPERTY_ID`` setting.", "response": "def google_analytics(parser, token):\n \"\"\"\n Google Analytics tracking template tag.\n\n Renders Javascript code to track page visits. You must supply\n your website property ID (as a string) in the\n ``GOOGLE_ANALYTICS_PROPERTY_ID`` setting.\n \"\"\"\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return GoogleAnalyticsNode()"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns a javascript code that can be used to display the page visits in Google Analytics.", "response": "def google_analytics_js(parser, token):\n \"\"\"\n Google Analytics tracking template tag.\n\n Renders Javascript code to track page visits. You must supply\n your website property ID (as a string) in the\n ``GOOGLE_ANALYTICS_JS_PROPERTY_ID`` setting.\n \"\"\"\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return GoogleAnalyticsJsNode()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef rating_mailru(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return RatingMailruNode()", "response": "This template tag renders Javascript code to track page visits."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef clicky(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return ClickyNode()", "response": "This is a helper function that returns a Clicky tracking template tag that can be used to track page visits."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nrender the top Javascript code for Chartbeat.", "response": "def chartbeat_top(parser, token):\n \"\"\"\n Top Chartbeat template tag.\n\n Render the top Javascript code for Chartbeat.\n \"\"\"\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return ChartbeatTopNode()"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ntops Chartbeat template tag.", "response": "def chartbeat_bottom(parser, token):\n \"\"\"\n Bottom Chartbeat template tag.\n\n Render the bottom Javascript code for Chartbeat. You must supply\n your Chartbeat User ID (as a string) in the ``CHARTBEAT_USER_ID``\n setting.\n \"\"\"\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return ChartbeatBottomNode()"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef woopra(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return WoopraNode()", "response": "A Woopra tracking template tag."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef spring_metrics(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return SpringMetricsNode()", "response": "A Spring Metrics tracking template tag."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsetting up surveys for the current user.", "response": "def kiss_insights(parser, token):\n \"\"\"\n KISSinsights set-up template tag.\n\n Renders Javascript code to set-up surveys. You must supply\n your account number and site code in the\n ``KISS_INSIGHTS_ACCOUNT_NUMBER`` and ``KISS_INSIGHTS_SITE_CODE``\n settings.\n \"\"\"\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return KissInsightsNode()"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef matomo(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return MatomoNode()", "response": "Matomo tracking template tag."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef snapengage(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return SnapEngageNode()", "response": "This function returns a SnapEngageNode instance."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef performable(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return PerformableNode()", "response": "A simple function that returns a PerformableNode that can be used to track the current time."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns a timestamp from a datetime. datetime object.", "response": "def _timestamp(when):\n \"\"\"\n Python 2 compatibility for `datetime.timestamp()`.\n \"\"\"\n return (time.mktime(when.timetuple()) if sys.version_info < (3,) else\n when.timestamp())"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _hashable_bytes(data):\n if isinstance(data, bytes):\n return data\n elif isinstance(data, str):\n return data.encode('ascii') # Fail on anything non-ASCII.\n else:\n raise TypeError(data)", "response": "Coerce strings to hashable bytes."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns a SHA - 256 HMAC of the user_hash as expected by Intercom.", "response": "def intercom_user_hash(data):\n \"\"\"\n Return a SHA-256 HMAC `user_hash` as expected by Intercom, if configured.\n\n Return None if the `INTERCOM_HMAC_SECRET_KEY` setting is not configured.\n \"\"\"\n if getattr(settings, 'INTERCOM_HMAC_SECRET_KEY', None):\n return hmac.new(\n key=_hashable_bytes(settings.INTERCOM_HMAC_SECRET_KEY),\n msg=_hashable_bytes(data),\n digestmod=hashlib.sha256,\n ).hexdigest()\n else:\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef uservoice(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return UserVoiceNode()", "response": "A user voice tracking template tag."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef piwik(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return PiwikNode()", "response": "This function returns a Piwik tracking template tag that can be used to track page visits."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn a value from django. conf. settings.", "response": "def get_required_setting(setting, value_re, invalid_msg):\n \"\"\"\n Return a constant from ``django.conf.settings``. The `setting`\n argument is the constant name, the `value_re` argument is a regular\n expression used to validate the setting value and the `invalid_msg`\n argument is used as exception message if the value is not valid.\n \"\"\"\n try:\n value = getattr(settings, setting)\n except AttributeError:\n raise AnalyticalException(\"%s setting: not found\" % setting)\n if not value:\n raise AnalyticalException(\"%s setting is not set\" % setting)\n value = str(value)\n if not value_re.search(value):\n raise AnalyticalException(\"%s setting: %s: '%s'\"\n % (setting, invalid_msg, value))\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngetting the user instance from the template context if possible.", "response": "def get_user_from_context(context):\n \"\"\"\n Get the user instance from the template context, if possible.\n\n If the context does not contain a `request` or `user` attribute,\n `None` is returned.\n \"\"\"\n try:\n return context['user']\n except KeyError:\n pass\n try:\n request = context['request']\n return request.user\n except (KeyError, AttributeError):\n pass\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_identity(context, prefix=None, identity_func=None, user=None):\n if prefix is not None:\n try:\n return context['%s_identity' % prefix]\n except KeyError:\n pass\n try:\n return context['analytical_identity']\n except KeyError:\n pass\n if getattr(settings, 'ANALYTICAL_AUTO_IDENTIFY', True):\n try:\n if user is None:\n user = get_user_from_context(context)\n if get_user_is_authenticated(user):\n if identity_func is not None:\n return identity_func(user)\n else:\n return user.get_username()\n except (KeyError, AttributeError):\n pass\n return None", "response": "Get the identity of a logged in user from a template context."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_domain(context, prefix):\n domain = context.get('%s_domain' % prefix)\n if domain is None:\n domain = context.get('analytical_domain')\n if domain is None:\n domain = getattr(settings, '%s_DOMAIN' % prefix.upper(), None)\n if domain is None:\n domain = getattr(settings, 'ANALYTICAL_DOMAIN', None)\n if domain is None:\n if 'django.contrib.sites' in settings.INSTALLED_APPS:\n from django.contrib.sites.models import Site\n try:\n domain = Site.objects.get_current().domain\n except (ImproperlyConfigured, Site.DoesNotExist):\n pass\n return domain", "response": "Get the domain used for tracking code."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef is_internal_ip(context, prefix=None):\n try:\n request = context['request']\n remote_ip = request.META.get('HTTP_X_FORWARDED_FOR', '')\n if not remote_ip:\n remote_ip = request.META.get('REMOTE_ADDR', '')\n if not remote_ip:\n return False\n\n internal_ips = None\n if prefix is not None:\n internal_ips = getattr(settings, '%s_INTERNAL_IPS' % prefix, None)\n if internal_ips is None:\n internal_ips = getattr(settings, 'ANALYTICAL_INTERNAL_IPS', None)\n if internal_ips is None:\n internal_ips = getattr(settings, 'INTERNAL_IPS', None)\n\n return remote_ip in (internal_ips or [])\n except (KeyError, AttributeError):\n return False", "response": "Returns True if the visitor is coming from an internal IP address."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef mixpanel(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return MixpanelNode()", "response": "A mixpanel template tag that tracks page visits."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef gosquared(parser, token):\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return GoSquaredNode()", "response": "Returns a GoSquared tracking template tag."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn a set - up Olark chat.", "response": "def olark(parser, token):\n \"\"\"\n Olark set-up template tag.\n\n Renders Javascript code to set-up Olark chat. You must supply\n your site ID in the ``OLARK_SITE_ID`` setting.\n \"\"\"\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return OlarkNode()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a GaugesNode for the given token.", "response": "def gauges(parser, token):\n \"\"\"\n Gaug.es template tag.\n\n Renders Javascript code to gaug.es testing. You must supply\n your Site ID account number in the ``GAUGES_SITE_ID``\n setting.\n \"\"\"\n bits = token.split_contents()\n if len(bits) > 1:\n raise TemplateSyntaxError(\"'%s' takes no arguments\" % bits[0])\n return GaugesNode()"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef status_printer():\n last_len = [0]\n\n def p(s):\n s = next(spinner) + ' ' + s\n len_s = len(s)\n output = '\\r' + s + (' ' * max(last_len[0] - len_s, 0))\n sys.stdout.write(output)\n sys.stdout.flush()\n last_len[0] = len_s\n return p", "response": "Manage the printing and in - place updating of a string of characters\n\n ."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_or_guess_paths_to_mutate(paths_to_mutate):\n if paths_to_mutate is None:\n # Guess path with code\n this_dir = os.getcwd().split(os.sep)[-1]\n if isdir('lib'):\n return 'lib'\n elif isdir('src'):\n return 'src'\n elif isdir(this_dir):\n return this_dir\n elif isdir(this_dir.replace('-', '_')):\n return this_dir.replace('-', '_')\n elif isdir(this_dir.replace(' ', '_')):\n return this_dir.replace(' ', '_')\n elif isdir(this_dir.replace('-', '')):\n return this_dir.replace('-', '')\n elif isdir(this_dir.replace(' ', '')):\n return this_dir.replace(' ', '')\n else:\n raise FileNotFoundError(\n 'Could not figure out where the code to mutate is. '\n 'Please specify it on the command line using --paths-to-mutate, '\n 'or by adding \"paths_to_mutate=code_dir\" in setup.cfg to the [mutmut] section.')\n else:\n return paths_to_mutate", "response": "Guesses the path to mutate from the command line."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef do_apply(mutation_pk, dict_synonyms, backup):\n filename, mutation_id = filename_and_mutation_id_from_pk(int(mutation_pk))\n\n update_line_numbers(filename)\n\n context = Context(\n mutation_id=mutation_id,\n filename=filename,\n dict_synonyms=dict_synonyms,\n )\n mutate_file(\n backup=backup,\n context=context,\n )\n if context.number_of_performed_mutations == 0:\n raise RuntimeError('No mutations performed.')", "response": "Apply a specified mutant to the source code\n "}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef main(command, argument, argument2, paths_to_mutate, backup, runner, tests_dir,\n test_time_multiplier, test_time_base,\n swallow_output, use_coverage, dict_synonyms, cache_only, version,\n suspicious_policy, untested_policy, pre_mutation, post_mutation,\n use_patch_file):\n \"\"\"return exit code, after performing an mutation test run.\n\n :return: the exit code from executing the mutation tests\n :rtype: int\n \"\"\"\n if version:\n print(\"mutmut version %s\" % __version__)\n return 0\n\n if use_coverage and use_patch_file:\n raise click.BadArgumentUsage(\"You can't combine --use-coverage and --use-patch\")\n\n valid_commands = ['run', 'results', 'apply', 'show', 'junitxml']\n if command not in valid_commands:\n raise click.BadArgumentUsage('%s is not a valid command, must be one of %s' % (command, ', '.join(valid_commands)))\n\n if command == 'results' and argument:\n raise click.BadArgumentUsage('The %s command takes no arguments' % command)\n\n dict_synonyms = [x.strip() for x in dict_synonyms.split(',')]\n\n if command in ('show', 'diff'):\n if not argument:\n print_result_cache()\n return 0\n\n if argument == 'all':\n print_result_cache(show_diffs=True, dict_synonyms=dict_synonyms, print_only_filename=argument2)\n return 0\n\n print(get_unified_diff(argument, dict_synonyms))\n return 0\n\n if use_coverage and not exists('.coverage'):\n raise FileNotFoundError('No .coverage file found. You must generate a coverage file to use this feature.')\n\n if command == 'results':\n print_result_cache()\n return 0\n\n if command == 'junitxml':\n print_result_cache_junitxml(dict_synonyms, suspicious_policy, untested_policy)\n return 0\n\n if command == 'apply':\n do_apply(argument, dict_synonyms, backup)\n return 0\n\n paths_to_mutate = get_or_guess_paths_to_mutate(paths_to_mutate)\n\n if not isinstance(paths_to_mutate, (list, tuple)):\n paths_to_mutate = [x.strip() for x in paths_to_mutate.split(',')]\n\n if not paths_to_mutate:\n raise click.BadOptionUsage('--paths-to-mutate', 'You must specify a list of paths to mutate. Either as a command line argument, or by setting paths_to_mutate under the section [mutmut] in setup.cfg')\n\n tests_dirs = []\n for p in tests_dir.split(':'):\n tests_dirs.extend(glob(p, recursive=True))\n\n for p in paths_to_mutate:\n for pt in tests_dir.split(':'):\n tests_dirs.extend(glob(p + '/**/' + pt, recursive=True))\n del tests_dir\n\n os.environ['PYTHONDONTWRITEBYTECODE'] = '1' # stop python from creating .pyc files\n\n using_testmon = '--testmon' in runner\n\n print(\"\"\"\n- Mutation testing starting -\n\nThese are the steps:\n1. A full test suite run will be made to make sure we\n can run the tests successfully and we know how long\n it takes (to detect infinite loops for example)\n2. Mutants will be generated and checked\n\nResults are stored in .mutmut-cache.\nPrint found mutants with `mutmut results`.\n\nLegend for output:\n\ud83c\udf89 Killed mutants. The goal is for everything to end up in this bucket.\n\u23f0 Timeout. Test suite took 10 times as long as the baseline so were killed.\n\ud83e\udd14 Suspicious. Tests took a long time, but not long enough to be fatal.\n\ud83d\ude41 Survived. This means your tests needs to be expanded.\n\"\"\")\n baseline_time_elapsed = time_test_suite(\n swallow_output=not swallow_output,\n test_command=runner,\n using_testmon=using_testmon\n )\n\n if using_testmon:\n copy('.testmondata', '.testmondata-initial')\n\n # if we're running in a mode with externally whitelisted lines\n if use_coverage or use_patch_file:\n covered_lines_by_filename = {}\n if use_coverage:\n coverage_data = read_coverage_data()\n else:\n assert use_patch_file\n covered_lines_by_filename = read_patch_data(use_patch_file)\n coverage_data = None\n\n def _exclude(context):\n try:\n covered_lines = covered_lines_by_filename[context.filename]\n except KeyError:\n if coverage_data is not None:\n covered_lines = coverage_data.lines(os.path.abspath(context.filename))\n covered_lines_by_filename[context.filename] = covered_lines\n else:\n covered_lines = None\n\n if covered_lines is None:\n return True\n current_line = context.current_line_index + 1\n if current_line not in covered_lines:\n return True\n return False\n else:\n def _exclude(context):\n del context\n return False\n\n if command != 'run':\n raise click.BadArgumentUsage(\"Invalid command %s\" % command)\n\n mutations_by_file = {}\n\n if argument is None:\n for path in paths_to_mutate:\n for filename in python_source_files(path, tests_dirs):\n update_line_numbers(filename)\n add_mutations_by_file(mutations_by_file, filename, _exclude, dict_synonyms)\n else:\n filename, mutation_id = filename_and_mutation_id_from_pk(int(argument))\n mutations_by_file[filename] = [mutation_id]\n\n total = sum(len(mutations) for mutations in mutations_by_file.values())\n\n print()\n print('2. Checking mutants')\n config = Config(\n swallow_output=not swallow_output,\n test_command=runner,\n exclude_callback=_exclude,\n baseline_time_elapsed=baseline_time_elapsed,\n backup=backup,\n dict_synonyms=dict_synonyms,\n total=total,\n using_testmon=using_testmon,\n cache_only=cache_only,\n tests_dirs=tests_dirs,\n hash_of_tests=hash_of_tests(tests_dirs),\n test_time_multiplier=test_time_multiplier,\n test_time_base=test_time_base,\n pre_mutation=pre_mutation,\n post_mutation=post_mutation,\n )\n\n try:\n run_mutation_tests(config=config, mutations_by_file=mutations_by_file)\n except Exception as e:\n traceback.print_exc()\n return compute_exit_code(config, e)\n else:\n return compute_exit_code(config)\n finally:\n print()", "response": "This function is the main function for the mutation test run."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nopen a subprocess and stream its output.", "response": "def popen_streaming_output(cmd, callback, timeout=None):\n \"\"\"Open a subprocess and stream its output without hard-blocking.\n\n :param cmd: the command to execute within the subprocess\n :type cmd: str\n\n :param callback: function that intakes the subprocess' stdout line by line.\n It is called for each line received from the subprocess' stdout stream.\n :type callback: Callable[[Context], bool]\n\n :param timeout: the timeout time of the subprocess\n :type timeout: float\n\n :raises TimeoutError: if the subprocess' execution time exceeds\n the timeout time\n\n :return: the return code of the executed subprocess\n :rtype: int\n \"\"\"\n if os.name == 'nt': # pragma: no cover\n process = subprocess.Popen(\n shlex.split(cmd),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n stdout = process.stdout\n else:\n master, slave = os.openpty()\n process = subprocess.Popen(\n shlex.split(cmd, posix=True),\n stdout=slave,\n stderr=slave\n )\n stdout = os.fdopen(master)\n os.close(slave)\n\n def kill(process_):\n \"\"\"Kill the specified process on Timer completion\"\"\"\n try:\n process_.kill()\n except OSError:\n pass\n\n # python 2-3 agnostic process timer\n timer = Timer(timeout, kill, [process])\n timer.setDaemon(True)\n timer.start()\n\n while process.returncode is None:\n try:\n if os.name == 'nt': # pragma: no cover\n line = stdout.readline()\n # windows gives readline() raw stdout as a b''\n # need to decode it\n line = line.decode(\"utf-8\")\n if line: # ignore empty strings and None\n callback(line.rstrip())\n else:\n while True:\n line = stdout.readline()\n if not line:\n break\n callback(line.rstrip())\n except (IOError, OSError):\n # This seems to happen on some platforms, including TravisCI.\n # It seems like it's ok to just let this pass here, you just\n # won't get as nice feedback.\n pass\n if not timer.is_alive():\n raise TimeoutError(\"subprocess running command '{}' timed out after {} seconds\".format(cmd, timeout))\n process.poll()\n\n # we have returned from the subprocess cancel the timer if it is running\n timer.cancel()\n\n return process.returncode"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef run_mutation(config, filename, mutation_id):\n context = Context(\n mutation_id=mutation_id,\n filename=filename,\n exclude=config.exclude_callback,\n dict_synonyms=config.dict_synonyms,\n config=config,\n )\n\n cached_status = cached_mutation_status(filename, mutation_id, config.hash_of_tests)\n if cached_status == BAD_SURVIVED:\n config.surviving_mutants += 1\n elif cached_status == BAD_TIMEOUT:\n config.surviving_mutants_timeout += 1\n elif cached_status == OK_KILLED:\n config.killed_mutants += 1\n elif cached_status == OK_SUSPICIOUS:\n config.suspicious_mutants += 1\n else:\n assert cached_status == UNTESTED, cached_status\n\n config.print_progress()\n\n if cached_status != UNTESTED:\n return cached_status\n\n if config.pre_mutation:\n result = subprocess.check_output(config.pre_mutation, shell=True).decode().strip()\n if result:\n print(result)\n\n try:\n number_of_mutations_performed = mutate_file(\n backup=True,\n context=context\n )\n assert number_of_mutations_performed\n start = time()\n try:\n survived = tests_pass(config)\n except TimeoutError:\n context.config.surviving_mutants_timeout += 1\n return BAD_TIMEOUT\n\n time_elapsed = time() - start\n if time_elapsed > config.test_time_base + (config.baseline_time_elapsed * config.test_time_multipler):\n config.suspicious_mutants += 1\n return OK_SUSPICIOUS\n\n if survived:\n context.config.surviving_mutants += 1\n return BAD_SURVIVED\n else:\n context.config.killed_mutants += 1\n return OK_KILLED\n finally:\n move(filename + '.bak', filename)\n\n if config.post_mutation:\n result = subprocess.check_output(config.post_mutation, shell=True).decode().strip()\n if result:\n print(result)", "response": "Run the mutation on the file."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef read_coverage_data():\n print('Using coverage data from .coverage file')\n # noinspection PyPackageRequirements,PyUnresolvedReferences\n from coverage import Coverage\n cov = Coverage('.coverage')\n cov.load()\n return cov.get_data()", "response": "Reads coverage data from. coverage file."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nadd mutations from a file to a dictionary.", "response": "def add_mutations_by_file(mutations_by_file, filename, exclude, dict_synonyms):\n \"\"\"\n :type mutations_by_file: dict[str, list[MutationID]]\n :type filename: str\n :type exclude: Callable[[Context], bool]\n :type dict_synonyms: list[str]\n \"\"\"\n with open(filename) as f:\n source = f.read()\n context = Context(\n source=source,\n filename=filename,\n exclude=exclude,\n dict_synonyms=dict_synonyms,\n )\n\n try:\n mutations_by_file[filename] = list_mutations(context)\n register_mutants(mutations_by_file)\n except Exception as e:\n raise RuntimeError('Failed while creating mutations for %s, for line \"%s\"' % (context.filename, context.current_source_line), e)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngives a path to a python source file or package directory yield the paths to the python source files that need to be mutated", "response": "def python_source_files(path, tests_dirs):\n \"\"\"Attempt to guess where the python source files to mutate are and yield\n their paths\n\n :param path: path to a python source file or package directory\n :type path: str\n\n :param tests_dirs: list of directory paths containing test files\n (we do not want to mutate these!)\n :type tests_dirs: list[str]\n\n :return: generator listing the paths to the python source files to mutate\n :rtype: Generator[str, None, None]\n \"\"\"\n if isdir(path):\n for root, dirs, files in os.walk(path):\n dirs[:] = [d for d in dirs if os.path.join(root, d) not in tests_dirs]\n for filename in files:\n if filename.endswith('.py'):\n yield os.path.join(root, filename)\n else:\n yield path"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef compute_exit_code(config, exception=None):\n code = 0\n if exception is not None:\n code = code | 1\n if config.surviving_mutants > 0:\n code = code | 2\n if config.surviving_mutants_timeout > 0:\n code = code | 4\n if config.suspicious_mutants > 0:\n code = code | 8\n return code", "response": "Compute an exit code for the mutmut mutation testing process."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef argument_mutation(children, context, **_):\n if len(context.stack) >= 3 and context.stack[-3].type in ('power', 'atom_expr'):\n stack_pos_of_power_node = -3\n elif len(context.stack) >= 4 and context.stack[-4].type in ('power', 'atom_expr'):\n stack_pos_of_power_node = -4\n else:\n return\n\n power_node = context.stack[stack_pos_of_power_node]\n\n if power_node.children[0].type == 'name' and power_node.children[0].value in context.dict_synonyms:\n c = children[0]\n if c.type == 'name':\n children = children[:]\n children[0] = Name(c.value + 'XX', start_pos=c.start_pos, prefix=c.prefix)\n return children", "response": "This function is used to mutate the argument list of a resource class."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef mutate(context):\n try:\n result = parse(context.source, error_recovery=False)\n except Exception:\n print('Failed to parse %s. Internal error from parso follows.' % context.filename)\n print('----------------------------------')\n raise\n mutate_list_of_nodes(result, context=context)\n mutated_source = result.get_code().replace(' not not ', ' ')\n if context.remove_newline_at_end:\n assert mutated_source[-1] == '\\n'\n mutated_source = mutated_source[:-1]\n if context.number_of_performed_mutations:\n # If we said we mutated the code, check that it has actually changed\n assert context.source != mutated_source\n context.mutated_source = mutated_source\n return mutated_source, context.number_of_performed_mutations", "response": "Mutates the source code of the current node."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef mutate_file(backup, context):\n with open(context.filename) as f:\n code = f.read()\n context.source = code\n if backup:\n with open(context.filename + '.bak', 'w') as f:\n f.write(code)\n result, number_of_mutations_performed = mutate(context)\n with open(context.filename, 'w') as f:\n f.write(result)\n return number_of_mutations_performed", "response": ":type backup: bool\n :type context: Context"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nconnect to the device.", "response": "def connect(self, timeout_sec=TIMEOUT_SEC):\n \"\"\"Connect to the device. If not connected within the specified timeout\n then an exception is thrown.\n \"\"\"\n self._central_manager.connectPeripheral_options_(self._peripheral, None)\n if not self._connected.wait(timeout_sec):\n raise RuntimeError('Failed to connect to device within timeout period!')"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ndisconnect from the device.", "response": "def disconnect(self, timeout_sec=TIMEOUT_SEC):\n \"\"\"Disconnect from the device. If not disconnected within the specified\n timeout then an exception is thrown.\n \"\"\"\n # Remove all the services, characteristics, and descriptors from the\n # lists of those items. Do this before disconnecting because they wont't\n # be accessible afterwards.\n for service in self.list_services():\n for char in service.list_characteristics():\n for desc in char.list_descriptors():\n descriptor_list().remove(desc)\n characteristic_list().remove(char)\n service_list().remove(service)\n # Now disconnect.\n self._central_manager.cancelPeripheralConnection_(self._peripheral)\n if not self._disconnected.wait(timeout_sec):\n raise RuntimeError('Failed to disconnect to device within timeout period!')"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncalls when advertisement data is received.", "response": "def _update_advertised(self, advertised):\n \"\"\"Called when advertisement data is received.\"\"\"\n # Advertisement data was received, pull out advertised service UUIDs and\n # name from advertisement data.\n if 'kCBAdvDataServiceUUIDs' in advertised:\n self._advertised = self._advertised + map(cbuuid_to_uuid, advertised['kCBAdvDataServiceUUIDs'])"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _characteristics_discovered(self, service):\n # Characteristics for the specified service were discovered. Update\n # set of discovered services and signal when all have been discovered.\n self._discovered_services.add(service)\n if self._discovered_services >= set(self._peripheral.services()):\n # Found all the services characteristics, finally time to fire the\n # service discovery complete event.\n self._discovered.set()", "response": "Called when all GATT characteristics have been discovered."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncalls when the specified characteristic has changed its value.", "response": "def _characteristic_changed(self, characteristic):\n \"\"\"Called when the specified characteristic has changed its value.\"\"\"\n # Called when a characteristic is changed. Get the on_changed handler\n # for this characteristic (if it exists) and call it.\n on_changed = self._char_on_changed.get(characteristic, None)\n if on_changed is not None:\n on_changed(characteristic.value().bytes().tobytes())\n # Also tell the characteristic that it has a new value.\n # First get the service that is associated with this characteristic.\n char = characteristic_list().get(characteristic)\n if char is not None:\n char._value_read.set()"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncalling when the specified descriptor has changed its value.", "response": "def _descriptor_changed(self, descriptor):\n \"\"\"Called when the specified descriptor has changed its value.\"\"\"\n # Tell the descriptor it has a new value to read.\n desc = descriptor_list().get(descriptor)\n if desc is not None:\n desc._value_read.set()"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nwaiting up to timeout_sec for the specified services and characteristics on the device.", "response": "def discover(self, service_uuids, char_uuids, timeout_sec=TIMEOUT_SEC):\n \"\"\"Wait up to timeout_sec for the specified services and characteristics\n to be discovered on the device. If the timeout is exceeded without\n discovering the services and characteristics then an exception is thrown.\n \"\"\"\n # Since OSX tells us when all services and characteristics are discovered\n # this function can just wait for that full service discovery.\n if not self._discovered.wait(timeout_sec):\n raise RuntimeError('Failed to discover device services within timeout period!')"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef rssi(self, timeout_sec=TIMEOUT_SEC):\n # Kick off query to get RSSI, then wait for it to return asyncronously\n # when the _rssi_changed() function is called.\n self._rssi_read.clear()\n self._peripheral.readRSSI()\n if not self._rssi_read.wait(timeout_sec):\n raise RuntimeError('Exceeded timeout waiting for RSSI value!')\n return self._rssi", "response": "Return the signal strength in decibels."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef read(self, timeout_sec=None):\n try:\n return self._queue.get(timeout=timeout_sec)\n except queue.Empty:\n # Timeout exceeded, return None to signify no data received.\n return None", "response": "Block until data is available to read from the UART."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef list_characteristics(self):\n paths = self._props.Get(_SERVICE_INTERFACE, 'Characteristics')\n return map(BluezGattCharacteristic,\n get_provider()._get_objects_by_path(paths))", "response": "Return a list of GATT characteristics that have been discovered for this service."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef start_notify(self, on_change):\n # Setup a closure to be the first step in handling the on change callback.\n # This closure will verify the characteristic is changed and pull out the\n # new value to pass to the user's on change callback.\n def characteristic_changed(iface, changed_props, invalidated_props):\n # Check that this change is for a GATT characteristic and it has a\n # new value.\n if iface != _CHARACTERISTIC_INTERFACE:\n return\n if 'Value' not in changed_props:\n return\n # Send the new value to the on_change callback.\n on_change(''.join(map(chr, changed_props['Value'])))\n # Hook up the property changed signal to call the closure above.\n self._props.connect_to_signal('PropertiesChanged', characteristic_changed)\n # Enable notifications for changes on the characteristic.\n self._characteristic.StartNotify()", "response": "Enable notification of changes for this characteristic on the\n specified on_change callback."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef list_descriptors(self):\n paths = self._props.Get(_CHARACTERISTIC_INTERFACE, 'Descriptors')\n return map(BluezGattDescriptor,\n get_provider()._get_objects_by_path(paths))", "response": "Return a list of GATT descriptors that have been discovered for this\n characteristic."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ncalling when the power state of the adapter has changed.", "response": "def _state_changed(self, state):\n \"\"\"Called when the power state changes.\"\"\"\n logger.debug('Adapter state change: {0}'.format(state))\n # Handle when powered on.\n if state == 5:\n self._powered_off.clear()\n self._powered_on.set()\n # Handle when powered off.\n elif state == 4:\n self._powered_on.clear()\n self._powered_off.set()"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nstarting scanning for BLE devices.", "response": "def start_scan(self, timeout_sec=TIMEOUT_SEC):\n \"\"\"Start scanning for BLE devices.\"\"\"\n get_provider()._central_manager.scanForPeripheralsWithServices_options_(None, None)\n self._is_scanning = True"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nstops scanning for BLE devices.", "response": "def stop_scan(self, timeout_sec=TIMEOUT_SEC):\n \"\"\"Stop scanning for BLE devices.\"\"\"\n get_provider()._central_manager.stopScan()\n self._is_scanning = False"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\npower off the adapter.", "response": "def power_off(self, timeout_sec=TIMEOUT_SEC):\n \"\"\"Power off Bluetooth.\"\"\"\n # Turn off bluetooth.\n self._powered_off.clear()\n IOBluetoothPreferenceSetControllerPowerState(0)\n if not self._powered_off.wait(timeout_sec):\n raise RuntimeError('Exceeded timeout waiting for adapter to power off!')"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nfind the first available device that supports this service and return it.", "response": "def find_device(cls, timeout_sec=TIMEOUT_SEC):\n \"\"\"Find the first available device that supports this service and return\n it, or None if no device is found. Will wait for up to timeout_sec\n seconds to find the device.\n \"\"\"\n return get_provider().find_device(service_uuids=cls.ADVERTISED, timeout_sec=timeout_sec)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef discover(cls, device, timeout_sec=TIMEOUT_SEC):\n device.discover(cls.SERVICES, cls.CHARACTERISTICS, timeout_sec)", "response": "Wait until the specified device has discovered the expected services\n and characteristics for this service."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef find_service(self, uuid):\n for service in self.list_services():\n if service.uuid == uuid:\n return service\n return None", "response": "Returns the first child service that has the specified\n UUID. Will return None if no such service is found."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nconnect to the device.", "response": "def connect(self, timeout_sec=TIMEOUT_SEC):\n \"\"\"Connect to the device. If not connected within the specified timeout\n then an exception is thrown.\n \"\"\"\n self._connected.clear()\n self._device.Connect()\n if not self._connected.wait(timeout_sec):\n raise RuntimeError('Exceeded timeout waiting to connect to device!')"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ndisconnect from the device.", "response": "def disconnect(self, timeout_sec=TIMEOUT_SEC):\n \"\"\"Disconnect from the device. If not disconnected within the specified\n timeout then an exception is thrown.\n \"\"\"\n self._disconnected.clear()\n self._device.Disconnect()\n if not self._disconnected.wait(timeout_sec):\n raise RuntimeError('Exceeded timeout waiting to disconnect from device!')"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning a list of GattService objects that have been discovered for this device.", "response": "def list_services(self):\n \"\"\"Return a list of GattService objects that have been discovered for\n this device.\n \"\"\"\n return map(BluezGattService,\n get_provider()._get_objects(_SERVICE_INTERFACE,\n self._device.object_path))"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns True if the device is able to discover the specified services and characteristics.", "response": "def discover(self, service_uuids, char_uuids, timeout_sec=TIMEOUT_SEC):\n \"\"\"Wait up to timeout_sec for the specified services and characteristics\n to be discovered on the device. If the timeout is exceeded without\n discovering the services and characteristics then an exception is thrown.\n \"\"\"\n # Turn expected values into a counter of each UUID for fast comparison.\n expected_services = set(service_uuids)\n expected_chars = set(char_uuids)\n # Loop trying to find the expected services for the device.\n start = time.time()\n while True:\n # Find actual services discovered for the device.\n actual_services = set(self.advertised)\n # Find actual characteristics discovered for the device.\n chars = map(BluezGattCharacteristic,\n get_provider()._get_objects(_CHARACTERISTIC_INTERFACE,\n self._device.object_path))\n actual_chars = set(map(lambda x: x.uuid, chars))\n # Compare actual discovered UUIDs with expected and return true if at\n # least the expected UUIDs are available.\n if actual_services >= expected_services and actual_chars >= expected_chars:\n # Found at least the expected services!\n return True\n # Couldn't find the devices so check if timeout has expired and try again.\n if time.time()-start >= timeout_sec:\n return False\n time.sleep(1)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn a list of UUIDs for services that are advertised by this Arc device.", "response": "def advertised(self):\n \"\"\"Return a list of UUIDs for services that are advertised by this\n device.\n \"\"\"\n uuids = []\n # Get UUIDs property but wrap it in a try/except to catch if the property\n # doesn't exist as it is optional.\n try:\n uuids = self._props.Get(_INTERFACE, 'UUIDs')\n except dbus.exceptions.DBusException as ex:\n # Ignore error if device has no UUIDs property (i.e. might not be\n # a BLE device).\n if ex.get_dbus_name() != 'org.freedesktop.DBus.Error.InvalidArgs':\n raise ex\n return [uuid.UUID(str(x)) for x in uuids]"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn the first child characteristic that has the specified UUID. Will return None if no such characteristic is found.", "response": "def find_characteristic(self, uuid):\n \"\"\"Return the first child characteristic found that has the specified\n UUID. Will return None if no characteristic that matches is found.\n \"\"\"\n for char in self.list_characteristics():\n if char.uuid == uuid:\n return char\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef find_descriptor(self, uuid):\n for desc in self.list_descriptors():\n if desc.uuid == uuid:\n return desc\n return None", "response": "Returns the first child descriptor that has the specified\n UUID. Will return None if no such child descriptor is found."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef read_value(self, timeout_sec=TIMEOUT_SEC):\n # Kick off a query to read the value of the characteristic, then wait\n # for the result to return asyncronously.\n self._value_read.clear()\n self._device._peripheral.readValueForCharacteristic_(self._characteristic)\n if not self._value_read.wait(timeout_sec):\n raise RuntimeError('Exceeded timeout waiting to read characteristic value!')\n return self._characteristic.value()", "response": "Read the value of this characteristic."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nwrites the specified value to this characteristic.", "response": "def write_value(self, value, write_type=0):\n \"\"\"Write the specified value to this characteristic.\"\"\"\n data = NSData.dataWithBytes_length_(value, len(value))\n self._device._peripheral.writeValue_forCharacteristic_type_(data,\n self._characteristic,\n write_type)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef start_notify(self, on_change):\n # Tell the device what callback to use for changes to this characteristic.\n self._device._notify_characteristic(self._characteristic, on_change)\n # Turn on notifications of characteristic changes.\n self._device._peripheral.setNotifyValue_forCharacteristic_(True,\n self._characteristic)", "response": "Enable notification of changes for this characteristic on the\n specified on_change callback."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nread the value of this descriptor.", "response": "def read_value(self):\n \"\"\"Read the value of this descriptor.\"\"\"\n pass\n # Kick off a query to read the value of the descriptor, then wait\n # for the result to return asyncronously.\n self._value_read.clear()\n self._device._peripheral.readValueForDescriptor(self._descriptor)\n if not self._value_read.wait(timeout_sec):\n raise RuntimeError('Exceeded timeout waiting to read characteristic value!')\n return self._value"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef start_scan(self, timeout_sec=TIMEOUT_SEC):\n self._scan_started.clear()\n self._adapter.StartDiscovery()\n if not self._scan_started.wait(timeout_sec):\n raise RuntimeError('Exceeded timeout waiting for adapter to start scanning!')", "response": "Start scanning for BLE devices with this adapter."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nstopping scanning for BLE devices with this adapter.", "response": "def stop_scan(self, timeout_sec=TIMEOUT_SEC):\n \"\"\"Stop scanning for BLE devices with this adapter.\"\"\"\n self._scan_stopped.clear()\n self._adapter.StopDiscovery()\n if not self._scan_stopped.wait(timeout_sec):\n raise RuntimeError('Exceeded timeout waiting for adapter to stop scanning!')"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef centralManagerDidUpdateState_(self, manager):\n logger.debug('centralManagerDidUpdateState called')\n # Notify adapter about changed central state.\n get_provider()._adapter._state_changed(manager.state())", "response": "Called when the central manager is powered on and ready to scan and connect\n to devices."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef centralManager_didDiscoverPeripheral_advertisementData_RSSI_(self, manager, peripheral, data, rssi):\n logger.debug('centralManager_didDiscoverPeripheral_advertisementData_RSSI called')\n # Log name of device found while scanning.\n #logger.debug('Saw device advertised with name: {0}'.format(peripheral.name()))\n # Make sure the device is added to the list of devices and then update\n # its advertisement state.\n device = device_list().get(peripheral)\n if device is None:\n device = device_list().add(peripheral, CoreBluetoothDevice(peripheral))\n device._update_advertised(data)", "response": "Called when the BLE adapter has discovered a device while scanning and has a new advertisement data for a device."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncalling when a device is connected.", "response": "def centralManager_didConnectPeripheral_(self, manager, peripheral):\n \"\"\"Called when a device is connected.\"\"\"\n logger.debug('centralManager_didConnectPeripheral called')\n # Setup peripheral delegate and kick off service discovery. For now just\n # assume all services need to be discovered.\n peripheral.setDelegate_(self)\n peripheral.discoverServices_(None)\n # Fire connected event for device.\n device = device_list().get(peripheral)\n if device is not None:\n device._set_connected()"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef centralManager_didDisconnectPeripheral_error_(self, manager, peripheral, error):\n logger.debug('centralManager_didDisconnectPeripheral called')\n # Get the device and remove it from the device list, then fire its\n # disconnected event.\n device = device_list().get(peripheral)\n if device is not None:\n # Fire disconnected event and remove device from device list.\n device._set_disconnected()\n device_list().remove(peripheral)", "response": "Called when a device is disconnected."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncall when services are discovered for a device.", "response": "def peripheral_didDiscoverServices_(self, peripheral, services):\n \"\"\"Called when services are discovered for a device.\"\"\"\n logger.debug('peripheral_didDiscoverServices called')\n # Make sure the discovered services are added to the list of known\n # services, and kick off characteristic discovery for each one.\n # NOTE: For some reason the services parameter is never set to a good\n # value, instead you must query peripheral.services() to enumerate the\n # discovered services.\n for service in peripheral.services():\n if service_list().get(service) is None:\n service_list().add(service, CoreBluetoothGattService(service))\n # Kick off characteristic discovery for this service. Just discover\n # all characteristics for now.\n peripheral.discoverCharacteristics_forService_(None, service)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef peripheral_didDiscoverCharacteristicsForService_error_(self, peripheral, service, error):\n logger.debug('peripheral_didDiscoverCharacteristicsForService_error called')\n # Stop if there was some kind of error.\n if error is not None:\n return\n # Make sure the discovered characteristics are added to the list of known\n # characteristics, and kick off descriptor discovery for each char.\n for char in service.characteristics():\n # Add to list of known characteristics.\n if characteristic_list().get(char) is None:\n characteristic_list().add(char, CoreBluetoothGattCharacteristic(char))\n # Start descriptor discovery.\n peripheral.discoverDescriptorsForCharacteristic_(char)\n # Notify the device about the discovered characteristics.\n device = device_list().get(peripheral)\n if device is not None:\n device._characteristics_discovered(service)", "response": "Called when the service has failed to discover characteristics."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef peripheral_didDiscoverDescriptorsForCharacteristic_error_(self, peripheral, characteristic, error):\n logger.debug('peripheral_didDiscoverDescriptorsForCharacteristic_error called')\n # Stop if there was some kind of error.\n if error is not None:\n return\n # Make sure the discovered descriptors are added to the list of known\n # descriptors.\n for desc in characteristic.descriptors():\n # Add to list of known descriptors.\n if descriptor_list().get(desc) is None:\n descriptor_list().add(desc, CoreBluetoothGattDescriptor(desc))", "response": "Called when a service is discovered for a given characteristic."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncalling when a peripheral value was read or updated.", "response": "def peripheral_didUpdateValueForCharacteristic_error_(self, peripheral, characteristic, error):\n \"\"\"Called when characteristic value was read or updated.\"\"\"\n logger.debug('peripheral_didUpdateValueForCharacteristic_error called')\n # Stop if there was some kind of error.\n if error is not None:\n return\n # Notify the device about the updated characteristic value.\n device = device_list().get(peripheral)\n if device is not None:\n device._characteristic_changed(characteristic)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ncalling when the descriptor value was read or updated.", "response": "def peripheral_didUpdateValueForDescriptor_error_(self, peripheral, descriptor, error):\n \"\"\"Called when descriptor value was read or updated.\"\"\"\n logger.debug('peripheral_didUpdateValueForDescriptor_error called')\n # Stop if there was some kind of error.\n if error is not None:\n return\n # Notify the device about the updated descriptor value.\n device = device_list().get(peripheral)\n if device is not None:\n device._descriptor_changed(descriptor)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncall when an error occurs when the RSSI value for the peripheral is read.", "response": "def peripheral_didReadRSSI_error_(self, peripheral, rssi, error):\n \"\"\"Called when a new RSSI value for the peripheral is available.\"\"\"\n logger.debug('peripheral_didReadRSSI_error called')\n # Note this appears to be completely undocumented at the time of this\n # writing. Can see more details at:\n # http://stackoverflow.com/questions/25952218/ios-8-corebluetooth-deprecated-rssi-methods\n # Stop if there was some kind of error.\n if error is not None:\n return\n # Notify the device about the updated RSSI value.\n device = device_list().get(peripheral)\n if device is not None:\n device._rssi_changed(rssi)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ninitializes the BLE provider.", "response": "def initialize(self):\n \"\"\"Initialize the BLE provider. Must be called once before any other\n calls are made to the provider.\n \"\"\"\n # Setup the central manager and its delegate.\n self._central_manager = CBCentralManager.alloc()\n self._central_manager.initWithDelegate_queue_options_(self._central_delegate,\n None, None)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nstart the OS s main loop to process asyncronous BLE events and thenrun the specified target function in a background thread.", "response": "def run_mainloop_with(self, target):\n \"\"\"Start the OS's main loop to process asyncronous BLE events and then\n run the specified target function in a background thread. Target\n function should be a function that takes no parameters and optionally\n return an integer response code. When the target function stops\n executing or returns with value then the main loop will be stopped and\n the program will exit with the returned code.\n\n Note that an OS main loop is required to process asyncronous BLE events\n and this function is provided as a convenience for writing simple tools\n and scripts that don't need to be full-blown GUI applications. If you\n are writing a GUI application that has a main loop (a GTK glib main loop\n on Linux, or a Cocoa main loop on OSX) then you don't need to call this\n function.\n \"\"\"\n # Create background thread to run user code.\n self._user_thread = threading.Thread(target=self._user_thread_main,\n args=(target,))\n self._user_thread.daemon = True\n self._user_thread.start()\n # Run main loop. This call will never return!\n try:\n AppHelper.runConsoleEventLoop(installInterrupt=True)\n except KeyboardInterrupt:\n AppHelper.stopEventLoop()\n sys.exit(0)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _user_thread_main(self, target):\n try:\n # Run user's code.\n return_code = target()\n # Assume good result (0 return code) if none is returned.\n if return_code is None:\n return_code = 0\n # Call exit on the main thread when user code has finished.\n AppHelper.callAfter(lambda: sys.exit(return_code))\n except Exception as ex:\n # Something went wrong. Raise the exception on the main thread to exit.\n AppHelper.callAfter(self._raise_error, sys.exc_info())", "response": "Main entry point for the thread that will run user s code."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef clear_cached_data(self):\n # Turn off bluetooth.\n if self._adapter.is_powered:\n self._adapter.power_off()\n # Delete cache files and suppress any stdout/err output.\n with open(os.devnull, 'w') as devnull:\n subprocess.call('rm ~/Library/Preferences/com.apple.Bluetooth.plist',\n shell=True, stdout=devnull, stderr=subprocess.STDOUT)\n subprocess.call('rm ~/Library/Preferences/ByHost/com.apple.Bluetooth.*.plist',\n shell=True, stdout=devnull, stderr=subprocess.STDOUT)", "response": "Clear the internal bluetooth device cache."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef disconnect_devices(self, service_uuids):\n # Get list of connected devices with specified services.\n cbuuids = map(uuid_to_cbuuid, service_uuids)\n for device in self._central_manager.retrieveConnectedPeripheralsWithServices_(cbuuids):\n self._central_manager.cancelPeripheralConnection_(device)", "response": "Disconnect any connected devices with any of the specified service UUIDs."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ninitializes the internal state of the object.", "response": "def initialize(self):\n \"\"\"Initialize bluez DBus communication. Must be called before any other\n calls are made!\n \"\"\"\n # Ensure GLib's threading is initialized to support python threads, and\n # make a default mainloop that all DBus objects will inherit. These\n # commands MUST execute before any other DBus commands!\n GObject.threads_init()\n dbus.mainloop.glib.threads_init()\n # Set the default main loop, this also MUST happen before other DBus calls.\n self._mainloop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n # Get the main DBus system bus and root bluez object.\n self._bus = dbus.SystemBus()\n self._bluez = dbus.Interface(self._bus.get_object('org.bluez', '/'),\n 'org.freedesktop.DBus.ObjectManager')"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef run_mainloop_with(self, target):\n # Spin up a background thread to run the target code.\n self._user_thread = threading.Thread(target=self._user_thread_main, args=(target,))\n self._user_thread.daemon = True # Don't let the user thread block exit.\n self._user_thread.start()\n # Spin up a GLib main loop in the main thread to process async BLE events.\n self._gobject_mainloop = GObject.MainLoop()\n try:\n self._gobject_mainloop.run() # Doesn't return until the mainloop ends.\n except KeyboardInterrupt:\n self._gobject_mainloop.quit()\n sys.exit(0)\n # Main loop finished. Check if an exception occured and throw it,\n # otherwise return the status code from the user code.\n if self._exception is not None:\n # Rethrow exception with its original stack trace following advice from:\n # http://nedbatchelder.com/blog/200711/rethrowing_exceptions_in_python.html\n raise_(self._exception[1], None, self._exception[2])\n else:\n sys.exit(self._return_code)", "response": "Start the OS s main loop to process asyncronous BLE events and then run the specified target function in a background thread."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _user_thread_main(self, target):\n try:\n # Wait for GLib main loop to start running before starting user code.\n while True:\n if self._gobject_mainloop is not None and self._gobject_mainloop.is_running():\n # Main loop is running, we should be ready to make bluez DBus calls.\n break\n # Main loop isn't running yet, give time back to other threads.\n time.sleep(0)\n # Run user's code.\n self._return_code = target()\n # Assume good result (0 return code) if none is returned.\n if self._return_code is None:\n self._return_code = 0\n # Signal the main loop to exit.\n self._gobject_mainloop.quit()\n except Exception as ex:\n # Something went wrong. Raise the exception on the main thread to\n # exit.\n self._exception = sys.exc_info()\n self._gobject_mainloop.quit()", "response": "Main entry point for the thread that will run user s code."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef clear_cached_data(self):\n # Go through and remove any device that isn't currently connected.\n for device in self.list_devices():\n # Skip any connected device.\n if device.is_connected:\n continue\n # Remove this device. First get the adapter associated with the device.\n adapter = dbus.Interface(self._bus.get_object('org.bluez', device._adapter),\n _ADAPTER_INTERFACE)\n # Now call RemoveDevice on the adapter to remove the device from\n # bluez's DBus hierarchy.\n adapter.RemoveDevice(device._device.object_path)", "response": "Clear any internally cached BLE device data."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef disconnect_devices(self, service_uuids=[]):\n service_uuids = set(service_uuids)\n for device in self.list_devices():\n # Skip devices that aren't connected.\n if not device.is_connected:\n continue\n device_uuids = set(map(lambda x: x.uuid, device.list_services()))\n if device_uuids >= service_uuids:\n # Found a device that has at least the requested services, now\n # disconnect from it.\n device.disconnect()", "response": "Disconnect any connected devices that have the specified list of\n service UUIDs."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _get_objects(self, interface, parent_path='/org/bluez'):\n # Iterate through all the objects in bluez's DBus hierarchy and return\n # any that implement the requested interface under the specified path.\n parent_path = parent_path.lower()\n objects = []\n for opath, interfaces in iteritems(self._bluez.GetManagedObjects()):\n if interface in interfaces.keys() and opath.lower().startswith(parent_path):\n objects.append(self._bus.get_object('org.bluez', opath))\n return objects", "response": "Return a list of all bluez DBus objects that implement the requested\n interface name and are under the specified path."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _get_objects_by_path(self, paths):\n return map(lambda x: self._bus.get_object('org.bluez', x), paths)", "response": "Return a list of all bluez DBus objects from the provided list of paths."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nprinting tree of all bluez objects useful for debugging.", "response": "def _print_tree(self):\n \"\"\"Print tree of all bluez objects, useful for debugging.\"\"\"\n # This is based on the bluez sample code get-managed-objects.py.\n objects = self._bluez.GetManagedObjects()\n for path in objects.keys():\n print(\"[ %s ]\" % (path))\n interfaces = objects[path]\n for interface in interfaces.keys():\n if interface in [\"org.freedesktop.DBus.Introspectable\",\n \"org.freedesktop.DBus.Properties\"]:\n continue\n print(\" %s\" % (interface))\n properties = interfaces[interface]\n for key in properties.keys():\n print(\" %s = %s\" % (key, properties[key]))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning a list of all the devices that advertise the specified service UUIDs and have the specified name.", "response": "def find_devices(self, service_uuids=[], name=None):\n \"\"\"Return devices that advertise the specified service UUIDs and/or have\n the specified name. Service_uuids should be a list of Python uuid.UUID\n objects and is optional. Name is a string device name to look for and is\n also optional. Will not block, instead it returns immediately with a\n list of found devices (which might be empty).\n \"\"\"\n # Convert service UUID list to counter for quicker comparison.\n expected = set(service_uuids)\n # Grab all the devices.\n devices = self.list_devices()\n # Filter to just the devices that have the requested service UUID/name.\n found = []\n for device in devices:\n if name is not None:\n if device.name == name:\n # Check if the name matches and add the device.\n found.append(device)\n else:\n # Check if the advertised UUIDs have at least the expected UUIDs.\n actual = set(device.advertised)\n if actual >= expected:\n found.append(device)\n return found"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC):\n start = time.time()\n while True:\n # Call find_devices and grab the first result if any are found.\n found = self.find_devices(service_uuids, name)\n if len(found) > 0:\n return found[0]\n # No device was found. Check if the timeout is exceeded and wait to\n # try again.\n if time.time()-start >= timeout_sec:\n # Failed to find a device within the timeout.\n return None\n time.sleep(1)", "response": "Find a device that advertises the specified service UUIDs or returns None."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_all(self, cbobjects):\n try:\n with self._lock:\n return [self._metadata[x] for x in cbobjects]\n except KeyError:\n # Note that if this error gets thrown then the assumption that OSX\n # will pass back to callbacks the exact CoreBluetooth objects that\n # were used previously is broken! (i.e. the CoreBluetooth objects\n # are not stateless)\n raise RuntimeError('Failed to find expected metadata for CoreBluetooth object!')", "response": "Retrieve a list of metadata objects associated with the specified CoreBluetooth objects."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nadding the specified CoreBluetooth item with the associated metadata.", "response": "def add(self, cbobject, metadata):\n \"\"\"Add the specified CoreBluetooth item with the associated metadata if\n it doesn't already exist. Returns the newly created or preexisting\n metadata item.\n \"\"\"\n with self._lock:\n if cbobject not in self._metadata:\n self._metadata[cbobject] = metadata\n return self._metadata[cbobject]"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nremove any metadata associated with the provided CoreBluetooth object.", "response": "def remove(self, cbobject):\n \"\"\"Remove any metadata associated with the provided CoreBluetooth object.\n \"\"\"\n with self._lock:\n if cbobject in self._metadata:\n del self._metadata[cbobject]"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef cbuuid_to_uuid(cbuuid):\n data = cbuuid.data().bytes()\n\n template = '{:0>8}-0000-1000-8000-00805f9b34fb' if len(data) <= 4 else '{:0>32}'\n value = template.format(hexlify(data.tobytes()[:16]).decode('ascii'))\n return uuid.UUID(hex=value)", "response": "Convert Objective - C CBUUID type to native Python UUID type."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nsets the red green blue color of the bulb.", "response": "def set_color(self, r, g, b):\n \"\"\"Set the red, green, blue color of the bulb.\"\"\"\n # See more details on the bulb's protocol from this guide:\n # https://learn.adafruit.com/reverse-engineering-a-bluetooth-low-energy-light-bulb/overview\n command = '\\x58\\x01\\x03\\x01\\xFF\\x00{0}{1}{2}'.format(chr(r & 0xFF),\n chr(g & 0xFF),\n chr(b & 0xFF))\n self._color.write_value(command)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn an instance of the BLE provider for the current platform.", "response": "def get_provider():\n \"\"\"Return an instance of the BLE provider for the current platform.\"\"\"\n global _provider\n # Set the provider based on the current platform.\n if _provider is None:\n if sys.platform.startswith('linux'):\n # Linux platform\n from .bluez_dbus.provider import BluezProvider\n _provider = BluezProvider()\n elif sys.platform == 'darwin':\n # Mac OSX platform\n from .corebluetooth.provider import CoreBluetoothProvider\n _provider = CoreBluetoothProvider()\n else:\n # Unsupported platform\n raise RuntimeError('Sorry the {0} platform is not supported by the BLE library!'.format(sys.platform))\n return _provider"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nconverting the byte array to a BigInteger", "response": "def toBigInt(byteArray):\n \"\"\"Convert the byte array to a BigInteger\"\"\"\n array = byteArray[::-1] # reverse array\n out = 0\n for key, value in enumerate(array):\n decoded = struct.unpack(\"B\", bytes([value]))[0]\n out = out | decoded << key * 8\n return out"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nencrypts the login and passwd using the google publickey", "response": "def encryptPassword(self, login, passwd):\n \"\"\"Encrypt credentials using the google publickey, with the\n RSA algorithm\"\"\"\n\n # structure of the binary key:\n #\n # *-------------------------------------------------------*\n # | modulus_length | modulus | exponent_length | exponent |\n # *-------------------------------------------------------*\n #\n # modulus_length and exponent_length are uint32\n binaryKey = b64decode(config.GOOGLE_PUBKEY)\n # modulus\n i = utils.readInt(binaryKey, 0)\n modulus = utils.toBigInt(binaryKey[4:][0:i])\n # exponent\n j = utils.readInt(binaryKey, i + 4)\n exponent = utils.toBigInt(binaryKey[i + 8:][0:j])\n\n # calculate SHA1 of the pub key\n digest = hashes.Hash(hashes.SHA1(), backend=default_backend())\n digest.update(binaryKey)\n h = b'\\x00' + digest.finalize()[0:4]\n\n # generate a public key\n der_data = encode_dss_signature(modulus, exponent)\n publicKey = load_der_public_key(der_data, backend=default_backend())\n\n # encrypt email and password using pubkey\n to_be_encrypted = login.encode() + b'\\x00' + passwd.encode()\n ciphertext = publicKey.encrypt(\n to_be_encrypted,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA1()),\n algorithm=hashes.SHA1(),\n label=None\n )\n )\n\n return urlsafe_b64encode(h + ciphertext)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the default set of request headers which can later be expanded based on the request type.", "response": "def getHeaders(self, upload_fields=False):\n \"\"\"Return the default set of request headers, which\n can later be expanded, based on the request type\"\"\"\n\n if upload_fields:\n headers = self.deviceBuilder.getDeviceUploadHeaders()\n else:\n headers = self.deviceBuilder.getBaseHeaders()\n if self.gsfId is not None:\n headers[\"X-DFE-Device-Id\"] = \"{0:x}\".format(self.gsfId)\n if self.authSubToken is not None:\n headers[\"Authorization\"] = \"GoogleLogin auth=%s\" % self.authSubToken\n if self.device_config_token is not None:\n headers[\"X-DFE-Device-Config-Token\"] = self.device_config_token\n if self.deviceCheckinConsistencyToken is not None:\n headers[\"X-DFE-Device-Checkin-Consistency-Token\"] = self.deviceCheckinConsistencyToken\n if self.dfeCookie is not None:\n headers[\"X-DFE-Cookie\"] = self.dfeCookie\n return headers"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef uploadDeviceConfig(self):\n\n upload = googleplay_pb2.UploadDeviceConfigRequest()\n upload.deviceConfiguration.CopyFrom(self.deviceBuilder.getDeviceConfig())\n headers = self.getHeaders(upload_fields=True)\n stringRequest = upload.SerializeToString()\n response = requests.post(UPLOAD_URL, data=stringRequest,\n headers=headers,\n verify=ssl_verify,\n timeout=60,\n proxies=self.proxies_config)\n response = googleplay_pb2.ResponseWrapper.FromString(response.content)\n try:\n if response.payload.HasField('uploadDeviceConfigResponse'):\n self.device_config_token = response.payload.uploadDeviceConfigResponse\n self.device_config_token = self.device_config_token.uploadDeviceConfigToken\n except ValueError:\n pass", "response": "Upload the fake device configuration of the fake device\n selected in the __init__ methodi to the google account."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef login(self, email=None, password=None, gsfId=None, authSubToken=None):\n if email is not None and password is not None:\n # First time setup, where we obtain an ac2dm token and\n # upload device information\n\n encryptedPass = self.encryptPassword(email, password).decode('utf-8')\n # AC2DM token\n params = self.deviceBuilder.getLoginParams(email, encryptedPass)\n params['service'] = 'ac2dm'\n params['add_account'] = '1'\n params['callerPkg'] = 'com.google.android.gms'\n headers = self.deviceBuilder.getAuthHeaders(self.gsfId)\n headers['app'] = 'com.google.android.gsm'\n response = requests.post(AUTH_URL, data=params, verify=ssl_verify,\n proxies=self.proxies_config)\n data = response.text.split()\n params = {}\n for d in data:\n if \"=\" not in d:\n continue\n k, v = d.split(\"=\", 1)\n params[k.strip().lower()] = v.strip()\n if \"auth\" in params:\n ac2dmToken = params[\"auth\"]\n elif \"error\" in params:\n if \"NeedsBrowser\" in params[\"error\"]:\n raise SecurityCheckError(\"Security check is needed, try to visit \"\n \"https://accounts.google.com/b/0/DisplayUnlockCaptcha \"\n \"to unlock, or setup an app-specific password\")\n raise LoginError(\"server says: \" + params[\"error\"])\n else:\n raise LoginError(\"Auth token not found.\")\n\n self.gsfId = self.checkin(email, ac2dmToken)\n self.getAuthSubToken(email, encryptedPass)\n self.uploadDeviceConfig()\n elif gsfId is not None and authSubToken is not None:\n # no need to initialize API\n self.gsfId = gsfId\n self.setAuthSubToken(authSubToken)\n # check if token is valid with a simple search\n self.search('drv')\n else:\n raise LoginError('Either (email,pass) or (gsfId, authSubToken) is needed')", "response": "Login to your Google Account."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nsearches the play store for an app.", "response": "def search(self, query):\n \"\"\" Search the play store for an app.\n\n nb_result (int): is the maximum number of result to be returned\n\n offset (int): is used to take result starting from an index.\n \"\"\"\n if self.authSubToken is None:\n raise LoginError(\"You need to login before executing any request\")\n\n path = SEARCH_URL + \"?c=3&q={}\".format(requests.utils.quote(query))\n # FIXME: not sure if this toc call should be here\n self.toc()\n data = self.executeRequestApi2(path)\n if utils.hasPrefetch(data):\n response = data.preFetch[0].response\n else:\n response = data\n resIterator = response.payload.listResponse.doc\n return list(map(utils.parseProtobufObj, resIterator))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef details(self, packageName):\n path = DETAILS_URL + \"?doc={}\".format(requests.utils.quote(packageName))\n data = self.executeRequestApi2(path)\n return utils.parseProtobufObj(data.payload.detailsResponse.docV2)", "response": "Get app details from a package name."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngets several apps details from a list of package names.", "response": "def bulkDetails(self, packageNames):\n \"\"\"Get several apps details from a list of package names.\n\n This is much more efficient than calling N times details() since it\n requires only one request. If an item is not found it returns an empty object\n instead of throwing a RequestError('Item not found') like the details() function\n\n Args:\n packageNames (list): a list of app IDs (usually starting with 'com.').\n\n Returns:\n a list of dictionaries containing docv2 data, or None\n if the app doesn't exist\"\"\"\n\n params = {'au': '1'}\n req = googleplay_pb2.BulkDetailsRequest()\n req.docid.extend(packageNames)\n data = req.SerializeToString()\n message = self.executeRequestApi2(BULK_URL,\n post_data=data.decode(\"utf-8\"),\n content_type=CONTENT_TYPE_PROTO,\n params=params)\n response = message.payload.bulkDetailsResponse\n return [None if not utils.hasDoc(entry) else\n utils.parseProtobufObj(entry.doc)\n for entry in response.entry]"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef browse(self, cat=None, subCat=None):\n path = BROWSE_URL + \"?c=3\"\n if cat is not None:\n path += \"&cat={}\".format(requests.utils.quote(cat))\n if subCat is not None:\n path += \"&ctr={}\".format(requests.utils.quote(subCat))\n data = self.executeRequestApi2(path)\n\n return utils.parseProtobufObj(data.payload.browseResponse)", "response": "Browse apps and return a list of apps with the same category and subcategory."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef reviews(self, packageName, filterByDevice=False, sort=2,\n nb_results=None, offset=None):\n \"\"\"Browse reviews for an application\n\n Args:\n packageName (str): app unique ID.\n filterByDevice (bool): filter results for current device\n sort (int): sorting criteria (values are unknown)\n nb_results (int): max number of reviews to return\n offset (int): return reviews starting from an offset value\n\n Returns:\n dict object containing all the protobuf data returned from\n the api\n \"\"\"\n # TODO: select the number of reviews to return\n path = REVIEWS_URL + \"?doc={}&sort={}\".format(requests.utils.quote(packageName), sort)\n if nb_results is not None:\n path += \"&n={}\".format(nb_results)\n if offset is not None:\n path += \"&o={}\".format(offset)\n if filterByDevice:\n path += \"&dfil=1\"\n data = self.executeRequestApi2(path)\n output = []\n for review in data.payload.reviewResponse.getResponse.review:\n output.append(utils.parseProtobufObj(review))\n return output", "response": "Browse reviews for an application and return a list of all the protobuf data returned from the api"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef delivery(self, packageName, versionCode=None, offerType=1,\n downloadToken=None, expansion_files=False):\n \"\"\"Download an already purchased app.\n\n Args:\n packageName (str): app unique ID (usually starting with 'com.')\n versionCode (int): version to download\n offerType (int): different type of downloads (mostly unused for apks)\n downloadToken (str): download token returned by 'purchase' API\n progress_bar (bool): wether or not to print a progress bar to stdout\n\n Returns:\n Dictionary containing apk data and a list of expansion files. As stated\n in android documentation, there can be at most 2 expansion files, one with\n main content, and one for patching the main content. Their names should\n follow this format:\n\n [main|patch]...obb\n\n Data to build this name string is provided in the dict object. For more\n info check https://developer.android.com/google/play/expansion-files.html\n \"\"\"\n\n if versionCode is None:\n # pick up latest version\n versionCode = self.details(packageName).get('versionCode')\n\n params = {'ot': str(offerType),\n 'doc': packageName,\n 'vc': str(versionCode)}\n headers = self.getHeaders()\n if downloadToken is not None:\n params['dtok'] = downloadToken\n response = requests.get(DELIVERY_URL, headers=headers,\n params=params, verify=ssl_verify,\n timeout=60,\n proxies=self.proxies_config)\n response = googleplay_pb2.ResponseWrapper.FromString(response.content)\n if response.commands.displayErrorMessage != \"\":\n raise RequestError(response.commands.displayErrorMessage)\n elif response.payload.deliveryResponse.appDeliveryData.downloadUrl == \"\":\n raise RequestError('App not purchased')\n else:\n result = {}\n result['docId'] = packageName\n result['additionalData'] = []\n downloadUrl = response.payload.deliveryResponse.appDeliveryData.downloadUrl\n cookie = response.payload.deliveryResponse.appDeliveryData.downloadAuthCookie[0]\n cookies = {\n str(cookie.name): str(cookie.value)\n }\n result['file'] = self._deliver_data(downloadUrl, cookies)\n if not expansion_files:\n return result\n for obb in response.payload.deliveryResponse.appDeliveryData.additionalFile:\n a = {}\n # fileType == 0 -> main\n # fileType == 1 -> patch\n if obb.fileType == 0:\n obbType = 'main'\n else:\n obbType = 'patch'\n a['type'] = obbType\n a['versionCode'] = obb.versionCode\n a['file'] = self._deliver_data(obb.downloadUrl, None)\n result['additionalData'].append(a)\n return result", "response": "Download an already purchased app.\n\n Args:\n packageName (str): app unique ID (usually starting with 'com.')\n versionCode (int): version to download\n offerType (int): different type of downloads (mostly unused for apks)\n downloadToken (str): download token returned by 'purchase' API\n progress_bar (bool): wether or not to print a progress bar to stdout\n\n Returns:\n Dictionary containing apk data and a list of expansion files. As stated\n in android documentation, there can be at most 2 expansion files, one with\n main content, and one for patching the main content. Their names should\n follow this format:\n\n [main|patch]...obb\n\n Data to build this name string is provided in the dict object. For more\n info check https://developer.android.com/google/play/expansion-files.html"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef download(self, packageName, versionCode=None, offerType=1, expansion_files=False):\n\n if self.authSubToken is None:\n raise LoginError(\"You need to login before executing any request\")\n\n if versionCode is None:\n # pick up latest version\n appDetails = self.details(packageName).get('details').get('appDetails')\n versionCode = appDetails.get('versionCode')\n\n headers = self.getHeaders()\n params = {'ot': str(offerType),\n 'doc': packageName,\n 'vc': str(versionCode)}\n self.log(packageName)\n response = requests.post(PURCHASE_URL, headers=headers,\n params=params, verify=ssl_verify,\n timeout=60,\n proxies=self.proxies_config)\n\n response = googleplay_pb2.ResponseWrapper.FromString(response.content)\n if response.commands.displayErrorMessage != \"\":\n raise RequestError(response.commands.displayErrorMessage)\n else:\n dlToken = response.payload.buyResponse.downloadToken\n return self.delivery(packageName, versionCode, offerType, dlToken,\n expansion_files=expansion_files)", "response": "Download an app and return its raw data."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef http_connection(timeout):\n def wrapper(f):\n def wrapped(*args, **kwargs):\n if not ('connection' in kwargs) or not kwargs['connection']:\n connection = requests.Session()\n kwargs['connection'] = connection\n else:\n connection = kwargs['connection']\n\n if not getattr(connection, 'timeout', False):\n connection.timeout = timeout\n connection.headers.update({'Content-type': 'application/json'})\n return f(*args, **kwargs)\n return wraps(f)(wrapped)\n return wrapper", "response": "Decorator for HTTP connection."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ncreate a secure authentication token.", "response": "def create_token(self, data, options=None):\n \"\"\"\n Generates a secure authentication token.\n\n Our token format follows the JSON Web Token (JWT) standard:\n header.claims.signature\n\n Where:\n 1) 'header' is a stringified, base64-encoded JSON object containing version and algorithm information.\n 2) 'claims' is a stringified, base64-encoded JSON object containing a set of claims:\n Library-generated claims:\n 'iat' -> The issued at time in seconds since the epoch as a number\n 'd' -> The arbitrary JSON object supplied by the user.\n User-supplied claims (these are all optional):\n 'exp' (optional) -> The expiration time of this token, as a number of seconds since the epoch.\n 'nbf' (optional) -> The 'not before' time before which the token should be rejected (seconds since the epoch)\n 'admin' (optional) -> If set to true, this client will bypass all security rules (use this to authenticate servers)\n 'debug' (optional) -> 'set to true to make this client receive debug information about security rule execution.\n 'simulate' (optional, internal-only for now) -> Set to true to neuter all API operations (listens / puts\n will run security rules but not actually write or return data).\n 3) A signature that proves the validity of this token (see: http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-07)\n\n For base64-encoding we use URL-safe base64 encoding. This ensures that the entire token is URL-safe\n and could, for instance, be placed as a query argument without any encoding (and this is what the JWT spec requires).\n\n Args:\n data - a json serializable object of data to be included in the token\n options - An optional dictionary of additional claims for the token. Possible keys include:\n a) 'expires' -- A timestamp (as a number of seconds since the epoch) denoting a time after which\n this token should no longer be valid.\n b) 'notBefore' -- A timestamp (as a number of seconds since the epoch) denoting a time before\n which this token should be rejected by the server.\n c) 'admin' -- Set to true to bypass all security rules (use this for your trusted servers).\n d) 'debug' -- Set to true to enable debug mode (so you can see the results of Rules API operations)\n e) 'simulate' -- (internal-only for now) Set to true to neuter all API operations (listens / puts\n will run security rules but not actually write or return data)\n Returns:\n A signed Firebase Authentication Token\n Raises:\n ValueError: if an invalid key is specified in options\n \"\"\"\n if not options:\n options = {}\n options.update({'admin': self.admin, 'debug': self.debug})\n claims = self._create_options_claims(options)\n claims['v'] = self.TOKEN_VERSION\n claims['iat'] = int(time.mktime(time.gmtime()))\n claims['d'] = data\n return self._encode_token(self.secret, claims)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef make_put_request(url, data, params, headers, connection):\n timeout = getattr(connection, 'timeout')\n response = connection.put(url, data=data, params=params, headers=headers,\n timeout=timeout)\n if response.ok or response.status_code == 403:\n return response.json() if response.content else None\n else:\n response.raise_for_status()", "response": "This function is a helper function that makes an HTTP PUT request to the firebase server."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_user(self):\n token = self.authenticator.create_token(self.extra)\n user_id = self.extra.get('id')\n return FirebaseUser(self.email, token, self.provider, user_id)", "response": "Method that gets the authenticated user. The returning user has\n the token email and provider data. The returning user has\n the token email and provider data. The returning user has\n the user id and the provider data."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _build_endpoint_url(self, url, name=None):\n if not url.endswith(self.URL_SEPERATOR):\n url = url + self.URL_SEPERATOR\n if name is None:\n name = ''\n return '%s%s%s' % (urlparse.urljoin(self.dsn, url), name,\n self.NAME_EXTENSION)", "response": "Method that builds a full url with the given url and the snapshot name."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef post(self, url, data, params=None, headers=None, connection=None):\n params = params or {}\n headers = headers or {}\n endpoint = self._build_endpoint_url(url, None)\n self._authenticate(params, headers)\n data = json.dumps(data, cls=JSONEncoder)\n return make_post_request(endpoint, data, params, headers,\n connection=connection)", "response": "Synchronously POST a resource."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef delete(self, url, name, params=None, headers=None, connection=None):\n if not name: name = ''\n params = params or {}\n headers = headers or {}\n endpoint = self._build_endpoint_url(url, name)\n self._authenticate(params, headers)\n return make_delete_request(endpoint, params, headers, connection=connection)", "response": "Synchronously delete a resource from the given URL."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef delete_async(self, url, name, callback=None, params=None, headers=None):\n if not name: name = ''\n params = params or {}\n headers = headers or {}\n endpoint = self._build_endpoint_url(url, name)\n self._authenticate(params, headers)\n process_pool.apply_async(make_delete_request,\n args=(endpoint, params, headers), callback=callback)", "response": "Asynchronous DELETE request with the process pool."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef do_filter(qs, keywords, exclude=False):\n and_q = Q()\n for keyword, value in iteritems(keywords):\n try:\n values = value.split(\",\")\n if len(values) > 0:\n or_q = Q()\n for value in values:\n or_q |= Q(**{keyword: value})\n and_q &= or_q\n except AttributeError:\n # value can be a bool\n and_q &= Q(**{keyword: value})\n if exclude:\n qs = qs.exclude(and_q)\n else:\n qs = qs.filter(and_q)\n return qs", "response": "Filter queryset based on keywords."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef filterchain_all(request, app, model, field, foreign_key_app_name,\n foreign_key_model_name, foreign_key_field_name, value):\n \"\"\"Returns filtered results followed by excluded results below.\"\"\"\n model_class = get_model(app, model)\n keywords = get_keywords(field, value)\n\n # SECURITY: Make sure all smart selects requests are opt-in\n foreign_model_class = get_model(foreign_key_app_name, foreign_key_model_name)\n if not any([(isinstance(f, ChainedManyToManyField) or\n isinstance(f, ChainedForeignKey))\n for f in foreign_model_class._meta.get_fields()]):\n raise PermissionDenied(\"Smart select disallowed\")\n\n # filter queryset using limit_choices_to\n limit_choices_to = get_limit_choices_to(foreign_key_app_name, foreign_key_model_name, foreign_key_field_name)\n queryset = get_queryset(model_class, limit_choices_to=limit_choices_to)\n\n filtered = list(do_filter(queryset, keywords))\n # Sort results if model doesn't include a default ordering.\n if not getattr(model_class._meta, 'ordering', False):\n sort_results(list(filtered))\n\n excluded = list(do_filter(queryset, keywords, exclude=True))\n # Sort results if model doesn't include a default ordering.\n if not getattr(model_class._meta, 'ordering', False):\n sort_results(list(excluded))\n\n # Empty choice to separate filtered and excluded results.\n empty_choice = {'value': \"\", 'display': \"---------\"}\n\n serialized_results = (\n serialize_results(filtered) +\n [empty_choice] +\n serialize_results(excluded)\n )\n\n return JsonResponse(serialized_results, safe=False)", "response": "Returns filtered results followed by excluded results below."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef media(self):\n media = super(JqueryMediaMixin, self).media\n\n js = []\n\n if JQUERY_URL:\n js.append(JQUERY_URL)\n elif JQUERY_URL is not False:\n vendor = '' if django.VERSION < (1, 9, 0) else 'vendor/jquery/'\n extra = '' if settings.DEBUG else '.min'\n\n jquery_paths = [\n '{}jquery{}.js'.format(vendor, extra),\n 'jquery.init.js',\n ]\n\n if USE_DJANGO_JQUERY:\n jquery_paths = ['admin/js/{}'.format(path) for path in jquery_paths]\n\n js.extend(jquery_paths)\n\n media += Media(js=js)\n return media", "response": "Media defined as a dynamic property instead of an inner class."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef media(self):\n media = super(ChainedSelect, self).media\n js = ['smart-selects/admin/js/chainedfk.js',\n 'smart-selects/admin/js/bindfields.js']\n media += Media(js=js)\n return media", "response": "Return a new Media object for this chained select."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nget possible choices for selection", "response": "def _get_available_choices(self, queryset, value):\n \"\"\"\n get possible choices for selection\n \"\"\"\n item = queryset.filter(pk=value).first()\n if item:\n try:\n pk = getattr(item, self.chained_model_field + \"_id\")\n filter = {self.chained_model_field: pk}\n except AttributeError:\n try: # maybe m2m?\n pks = getattr(item, self.chained_model_field).all().values_list('pk', flat=True)\n filter = {self.chained_model_field + \"__in\": pks}\n except AttributeError:\n try: # maybe a set?\n pks = getattr(item, self.chained_model_field + \"_set\").all().values_list('pk', flat=True)\n filter = {self.chained_model_field + \"__in\": pks}\n except AttributeError: # give up\n filter = {}\n filtered = list(get_model(self.to_app_name, self.to_model_name).objects.filter(**filter).distinct())\n if self.sort:\n sort_results(filtered)\n else:\n # invalid value for queryset\n filtered = []\n\n return filtered"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns a dynamic property instead of an inner class.", "response": "def media(self):\n \"\"\"Media defined as a dynamic property instead of an inner class.\"\"\"\n media = super(ChainedSelectMultiple, self).media\n js = ['smart-selects/admin/js/chainedm2m.js',\n 'smart-selects/admin/js/bindfields.js']\n if self.horizontal:\n # For horizontal mode add django filter horizontal javascript code\n js.extend([\"admin/js/core.js\",\n \"admin/js/SelectBox.js\",\n \"admin/js/SelectFilter2.js\"])\n media += Media(js=js)\n return media"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef unicode_sorter(input):\n\n # key1: compare words lowercase and replace umlauts according to DIN 5007\n key1 = input.lower()\n key1 = key1.replace(u\"\u00e4\", u\"a\")\n key1 = key1.replace(u\"\u00f6\", u\"o\")\n key1 = key1.replace(u\"\u00fc\", u\"u\")\n key1 = key1.replace(u\"\u00df\", u\"ss\")\n\n # key2: sort the lowercase word before the uppercase word and sort\n # the word with umlaut after the word without umlaut\n # key2=input.swapcase()\n\n # in case two words are the same according to key1, sort the words\n # according to key2.\n return key1", "response": "This function implements sort keys for the german language according to\n DIN 5007."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets the raw record for the given instance.", "response": "def get_raw_record(self, instance, update_fields=None):\n \"\"\"\n Gets the raw record.\n\n If `update_fields` is set, the raw record will be build with only\n the objectID and the given fields. Also, `_geoloc` and `_tags` will\n not be included.\n \"\"\"\n tmp = {'objectID': self.objectID(instance)}\n\n if update_fields:\n if isinstance(update_fields, str):\n update_fields = (update_fields,)\n\n for elt in update_fields:\n key = self.__translate_fields.get(elt, None)\n if key:\n tmp[key] = self.__named_fields[key](instance)\n else:\n for key, value in self.__named_fields.items():\n tmp[key] = value(instance)\n\n if self.geo_field:\n loc = self.geo_field(instance)\n\n if isinstance(loc, tuple):\n tmp['_geoloc'] = {'lat': loc[0], 'lng': loc[1]}\n elif isinstance(loc, dict):\n self._validate_geolocation(loc)\n tmp['_geoloc'] = loc\n elif isinstance(loc, list):\n [self._validate_geolocation(geo) for geo in loc]\n tmp['_geoloc'] = loc\n\n if self.tags:\n if callable(self.tags):\n tmp['_tags'] = self.tags(instance)\n if not isinstance(tmp['_tags'], list):\n tmp['_tags'] = list(tmp['_tags'])\n\n logger.debug('BUILD %s FROM %s', tmp['objectID'], self.model)\n return tmp"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning True if according to should_index the object should be indexed.", "response": "def _should_really_index(self, instance):\n \"\"\"Return True if according to should_index the object should be indexed.\"\"\"\n if self._should_index_is_method:\n is_method = inspect.ismethod(self.should_index)\n try:\n count_args = len(inspect.signature(self.should_index).parameters)\n except AttributeError:\n # noinspection PyDeprecation\n count_args = len(inspect.getargspec(self.should_index).args)\n\n if is_method or count_args is 1:\n # bound method, call with instance\n return self.should_index(instance)\n else:\n # unbound method, simply call without arguments\n return self.should_index()\n else:\n # property/attribute/Field, evaluate as bool\n attr_type = type(self.should_index)\n if attr_type is DeferredAttribute:\n attr_value = self.should_index.__get__(instance, None)\n elif attr_type is str:\n attr_value = getattr(instance, self.should_index)\n elif attr_type is property:\n attr_value = self.should_index.__get__(instance)\n else:\n raise AlgoliaIndexError('{} should be a boolean attribute or a method that returns a boolean.'.format(\n self.should_index))\n if type(attr_value) is not bool:\n raise AlgoliaIndexError(\"%s's should_index (%s) should be a boolean\" % (\n instance.__class__.__name__, self.should_index))\n return attr_value"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef save_record(self, instance, update_fields=None, **kwargs):\n if not self._should_index(instance):\n # Should not index, but since we don't now the state of the\n # instance, we need to send a DELETE request to ensure that if\n # the instance was previously indexed, it will be removed.\n self.delete_record(instance)\n return\n\n try:\n if update_fields:\n obj = self.get_raw_record(instance,\n update_fields=update_fields)\n result = self.__index.partial_update_object(obj)\n else:\n obj = self.get_raw_record(instance)\n result = self.__index.save_object(obj)\n logger.info('SAVE %s FROM %s', obj['objectID'], self.model)\n return result\n except AlgoliaException as e:\n if DEBUG:\n raise e\n else:\n logger.warning('%s FROM %s NOT SAVED: %s', obj['objectID'],\n self.model, e)", "response": "Saves the record.\n\n If `update_fields` is set, this method will use partial_update_object()\n and will update only the given fields (never `_geoloc` and `_tags`).\n\n For more information about partial_update_object:\n https://github.com/algolia/algoliasearch-client-python#update-an-existing-object-in-the-index"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef update_records(self, qs, batch_size=1000, **kwargs):\n tmp = {}\n for key, value in kwargs.items():\n name = self.__translate_fields.get(key, None)\n if name:\n tmp[name] = value\n\n batch = []\n objectsIDs = qs.only(self.custom_objectID).values_list(\n self.custom_objectID, flat=True)\n for elt in objectsIDs:\n tmp['objectID'] = elt\n batch.append(dict(tmp))\n\n if len(batch) >= batch_size:\n self.__index.partial_update_objects(batch)\n batch = []\n\n if len(batch) > 0:\n self.__index.partial_update_objects(batch)", "response": "This method updates multiple records. It takes a QuerySet and updates the record_size parameter and returns a list of dicts each containing the key - value pairs for each record."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef raw_search(self, query='', params=None):\n if params is None:\n params = {}\n\n try:\n return self.__index.search(query, params)\n except AlgoliaException as e:\n if DEBUG:\n raise e\n else:\n logger.warning('ERROR DURING SEARCH ON %s: %s', self.index_name, e)", "response": "Performs a search query and returns the parsed JSON."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the settings of the index.", "response": "def get_settings(self):\n \"\"\"Returns the settings of the index.\"\"\"\n try:\n logger.info('GET SETTINGS ON %s', self.index_name)\n return self.__index.get_settings()\n except AlgoliaException as e:\n if DEBUG:\n raise e\n else:\n logger.warning('ERROR DURING GET_SETTINGS ON %s: %s',\n self.model, e)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\napplies the settings to the index.", "response": "def set_settings(self):\n \"\"\"Applies the settings to the index.\"\"\"\n if not self.settings:\n return\n\n try:\n self.__index.set_settings(self.settings)\n logger.info('APPLY SETTINGS ON %s', self.index_name)\n except AlgoliaException as e:\n if DEBUG:\n raise e\n else:\n logger.warning('SETTINGS NOT APPLIED ON %s: %s',\n self.model, e)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef register(model):\n from algoliasearch_django import AlgoliaIndex, register\n\n def _algolia_engine_wrapper(index_class):\n if not issubclass(index_class, AlgoliaIndex):\n raise ValueError('Wrapped class must subclass AlgoliaIndex.')\n\n register(model, index_class)\n\n return index_class\n return _algolia_engine_wrapper", "response": "Decorator for Algolia engine register the given model class and wrapped AlgoliaIndex class with the Algolia engine"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nrun the management command.", "response": "def handle(self, *args, **options):\n \"\"\"Run the management command.\"\"\"\n self.stdout.write('Apply settings to index:')\n for model in get_registered_model():\n if options.get('model', None) and not (model.__name__ in\n options['model']):\n continue\n\n get_adapter(model).set_settings()\n self.stdout.write('\\t* {}'.format(model.__name__))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nregister a new model with Algolia engine.", "response": "def register(self, model, index_cls=AlgoliaIndex, auto_indexing=None):\n \"\"\"\n Registers the given model with Algolia engine.\n\n If the given model is already registered with Algolia engine, a\n RegistrationError will be raised.\n \"\"\"\n # Check for existing registration.\n if self.is_registered(model):\n raise RegistrationError(\n '{} is already registered with Algolia engine'.format(model))\n\n # Perform the registration.\n if not issubclass(index_cls, AlgoliaIndex):\n raise RegistrationError(\n '{} should be a subclass of AlgoliaIndex'.format(index_cls))\n index_obj = index_cls(model, self.client, self.__settings)\n self.__registered_models[model] = index_obj\n\n if (isinstance(auto_indexing, bool) and\n auto_indexing) or self.__auto_indexing:\n # Connect to the signalling framework.\n post_save.connect(self.__post_save_receiver, model)\n pre_delete.connect(self.__pre_delete_receiver, model)\n logger.info('REGISTER %s', model)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef unregister(self, model):\n if not self.is_registered(model):\n raise RegistrationError(\n '{} is not registered with Algolia engine'.format(model))\n # Perform the unregistration.\n del self.__registered_models[model]\n\n # Disconnect from the signalling framework.\n post_save.disconnect(self.__post_save_receiver, model)\n pre_delete.disconnect(self.__pre_delete_receiver, model)\n logger.info('UNREGISTER %s', model)", "response": "Unregisters the given model with Algolia engine."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the adapter associated with the given model.", "response": "def get_adapter(self, model):\n \"\"\"Returns the adapter associated with the given model.\"\"\"\n if not self.is_registered(model):\n raise RegistrationError(\n '{} is not registered with Algolia engine'.format(model))\n\n return self.__registered_models[model]"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nsave the record. If `update_fields` is set, this method will use partial_update_object() and will update only the given fields (never `_geoloc` and `_tags`). For more information about partial_update_object: https://github.com/algolia/algoliasearch-client-python#update-an-existing-object-in-the-index", "response": "def save_record(self, instance, **kwargs):\n \"\"\"Saves the record.\n\n If `update_fields` is set, this method will use partial_update_object()\n and will update only the given fields (never `_geoloc` and `_tags`).\n\n For more information about partial_update_object:\n https://github.com/algolia/algoliasearch-client-python#update-an-existing-object-in-the-index\n \"\"\"\n adapter = self.get_adapter_from_instance(instance)\n adapter.save_record(instance, **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ndeleting the record from the database.", "response": "def delete_record(self, instance):\n \"\"\"Deletes the record.\"\"\"\n adapter = self.get_adapter_from_instance(instance)\n adapter.delete_record(instance)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nupdate multiple records. This method is optimized for speed. It takes a QuerySet and updates the batch_size argument as a QuerySet and kwargs are passed to the update_records method.", "response": "def update_records(self, model, qs, batch_size=1000, **kwargs):\n \"\"\"\n Updates multiple records.\n\n This method is optimized for speed. It takes a QuerySet and the same\n arguments as QuerySet.update(). Optionally, you can specify the size\n of the batch send to Algolia with batch_size (default to 1000).\n\n >>> from algoliasearch_django import update_records\n >>> qs = MyModel.objects.filter(myField=False)\n >>> update_records(MyModel, qs, myField=True)\n >>> qs.update(myField=True)\n \"\"\"\n adapter = self.get_adapter(model)\n adapter.update_records(qs, batch_size=batch_size, **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef raw_search(self, model, query='', params=None):\n if params is None:\n params = {}\n\n adapter = self.get_adapter(model)\n return adapter.raw_search(query, params)", "response": "Performs a search query and returns the parsed JSON."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef reindex_all(self, model, batch_size=1000):\n adapter = self.get_adapter(model)\n return adapter.reindex_all(batch_size)", "response": "Reindex all the records."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef __post_save_receiver(self, instance, **kwargs):\n logger.debug('RECEIVE post_save FOR %s', instance.__class__)\n self.save_record(instance, **kwargs)", "response": "Signal handler for when a registered model has been saved."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nsignal handler for when a registered model has been deleted.", "response": "def __pre_delete_receiver(self, instance, **kwargs):\n \"\"\"Signal handler for when a registered model has been deleted.\"\"\"\n logger.debug('RECEIVE pre_delete FOR %s', instance.__class__)\n self.delete_record(instance)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nruns the management command.", "response": "def handle(self, *args, **options):\n \"\"\"Run the management command.\"\"\"\n batch_size = options.get('batchsize', None)\n if not batch_size:\n # py34-django18: batchsize is set to None if the user don't set\n # the value, instead of not be present in the dict\n batch_size = 1000\n\n self.stdout.write('The following models were reindexed:')\n for model in get_registered_model():\n if options.get('model', None) and not (model.__name__ in\n options['model']):\n continue\n\n counts = reindex_all(model, batch_size=batch_size)\n self.stdout.write('\\t* {} --> {}'.format(model.__name__, counts))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nrunning the management command.", "response": "def handle(self, *args, **options):\n \"\"\"Run the management command.\"\"\"\n self.stdout.write('Clear index:')\n for model in get_registered_model():\n if options.get('model', None) and not (model.__name__ in\n options['model']):\n continue\n\n clear_index(model)\n self.stdout.write('\\t* {}'.format(model.__name__))"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ndecodes the geohash to its exact values including the error Formula margins of the result.", "response": "def decode_exactly(geohash):\n \"\"\"\n Decode the geohash to its exact values, including the error\n margins of the result. Returns four float values: latitude,\n longitude, the plus/minus error for latitude (as a positive\n number) and the plus/minus error for longitude (as a positive\n number).\n \"\"\"\n lat_interval, lon_interval = (-90.0, 90.0), (-180.0, 180.0)\n lat_err, lon_err = 90.0, 180.0\n is_even = True\n for c in geohash:\n cd = __decodemap[c]\n for mask in [16, 8, 4, 2, 1]:\n if is_even: # adds longitude info\n lon_err /= 2\n if cd & mask:\n lon_interval = ((lon_interval[0]+lon_interval[1])/2, lon_interval[1])\n else:\n lon_interval = (lon_interval[0], (lon_interval[0]+lon_interval[1])/2)\n else: # adds latitude info\n lat_err /= 2\n if cd & mask:\n lat_interval = ((lat_interval[0]+lat_interval[1])/2, lat_interval[1])\n else:\n lat_interval = (lat_interval[0], (lat_interval[0]+lat_interval[1])/2)\n is_even = not is_even\n lat = (lat_interval[0] + lat_interval[1]) / 2\n lon = (lon_interval[0] + lon_interval[1]) / 2\n return lat, lon, lat_err, lon_err"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef decode(geohash):\n lat, lon, lat_err, lon_err = decode_exactly(geohash)\n # Format to the number of decimals that are known\n lats = \"%.*f\" % (max(1, int(round(-log10(lat_err)))) - 1, lat)\n lons = \"%.*f\" % (max(1, int(round(-log10(lon_err)))) - 1, lon)\n if '.' in lats: lats = lats.rstrip('0')\n if '.' in lons: lons = lons.rstrip('0')\n return lats, lons", "response": "Decode geohash returning two strings with latitude and longitude containing only relevant digits and with trailing zeroes removed."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nencoding a position given in float arguments latitude and longitude to WorkItem a geohash which will have the character count precision.", "response": "def encode(latitude, longitude, precision=12):\n \"\"\"\n Encode a position given in float arguments latitude, longitude to\n a geohash which will have the character count precision.\n \"\"\"\n lat_interval, lon_interval = (-90.0, 90.0), (-180.0, 180.0)\n geohash = []\n bits = [ 16, 8, 4, 2, 1 ]\n bit = 0\n ch = 0\n even = True\n while len(geohash) < precision:\n if even:\n mid = (lon_interval[0] + lon_interval[1]) / 2\n if longitude > mid:\n ch |= bits[bit]\n lon_interval = (mid, lon_interval[1])\n else:\n lon_interval = (lon_interval[0], mid)\n else:\n mid = (lat_interval[0] + lat_interval[1]) / 2\n if latitude > mid:\n ch |= bits[bit]\n lat_interval = (mid, lat_interval[1])\n else:\n lat_interval = (lat_interval[0], mid)\n even = not even\n if bit < 4:\n bit += 1\n else:\n geohash += __base32[ch]\n bit = 0\n ch = 0\n return ''.join(geohash)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef pad_to(unpadded, target_len):\n under = target_len - len(unpadded)\n if under <= 0:\n return unpadded\n return unpadded + (' ' * under)", "response": "Pad a string to the target length in characters."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\npads short rows to the length of the longest row to help render jagged CSV files", "response": "def normalize_cols(table):\n \"\"\"\n Pad short rows to the length of the longest row to help render \"jagged\"\n CSV files\n \"\"\"\n longest_row_len = max([len(row) for row in table])\n for row in table:\n while len(row) < longest_row_len:\n row.append('')\n return table"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef pad_cells(table):\n col_sizes = [max(map(len, col)) for col in zip(*table)]\n for row in table:\n for cell_num, cell in enumerate(row):\n row[cell_num] = pad_to(cell, col_sizes[cell_num])\n return table", "response": "Pad each cell in the table to the size of the largest cell in its column."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncreate the column dividers for a table with given column widths.", "response": "def horiz_div(col_widths, horiz, vert, padding):\n \"\"\"\n Create the column dividers for a table with given column widths.\n\n col_widths: list of column widths\n horiz: the character to use for a horizontal divider\n vert: the character to use for a vertical divider\n padding: amount of padding to add to each side of a column\n \"\"\"\n horizs = [horiz * w for w in col_widths]\n div = ''.join([padding * horiz, vert, padding * horiz])\n return div.join(horizs)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef add_dividers(row, divider, padding):\n div = ''.join([padding * ' ', divider, padding * ' '])\n return div.join(row)", "response": "Add dividers and padding to a row of cells and return a string."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef md_table(table, *, padding=DEFAULT_PADDING, divider='|', header_div='-'):\n table = normalize_cols(table)\n table = pad_cells(table)\n header = table[0]\n body = table[1:]\n\n col_widths = [len(cell) for cell in header]\n horiz = horiz_div(col_widths, header_div, divider, padding)\n\n header = add_dividers(header, divider, padding)\n body = [add_dividers(row, divider, padding) for row in body]\n\n table = [header, horiz]\n table.extend(body)\n table = [row.rstrip() for row in table]\n return '\\n'.join(table)", "response": "Convert a 2D array of items into a Markdown table."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncalculate base id and version from a resource id.", "response": "def baseId(resource_id, return_version=False):\n \"\"\"Calculate base id and version from a resource id.\n\n :params resource_id: Resource id.\n :params return_version: (optional) True if You need version, returns (resource_id, version).\n \"\"\"\n version = 0\n resource_id = resource_id + 0xC4000000 # 3288334336\n # TODO: version is broken due ^^, needs refactoring\n\n while resource_id > 0x01000000: # 16777216\n version += 1\n if version == 1:\n resource_id -= 0x80000000 # 2147483648 # 0x50000000 # 1342177280 ? || 0x2000000 # 33554432\n elif version == 2:\n resource_id -= 0x03000000 # 50331648\n else:\n resource_id -= 0x01000000 # 16777216\n\n if return_version:\n return resource_id, version - 67 # just correct \"magic number\"\n\n return resource_id"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef itemParse(item_data, full=True):\n # TODO: object\n # TODO: dynamically parse all data\n # TODO: make it less ugly\n # ItemRareType={NONE:0,RARE:1,LOCK:2,TOTW:3,PURPLE:4,TOTY:5,RB:6,GREEN:7,ORANGE:8,PINK:9,TEAL:10,TOTS:11,LEGEND:12,WC:13,UNICEF:14,OLDIMOTM:15,FUTTY:16,STORYMODE:17,CHAMPION:18,CMOTM:19,IMOTM:20,OTW:21,HALLOWEEN:22,MOVEMBER:23,SBC:24,SBCP:25,PROMOA:26,PROMOB:27,AWARD:28,BDAY:30,UNITED:31,FUTMAS:32,RTRC:33,PTGS:34,FOF:35,MARQUEE:36,CHAMPIONSHIP:37,EUMOTM:38,TOTT:39,RRC:40,RRR:41}\n return_data = {\n 'tradeId': item_data.get('tradeId'),\n 'buyNowPrice': item_data.get('buyNowPrice'),\n 'tradeState': item_data.get('tradeState'),\n 'bidState': item_data.get('bidState'),\n 'startingBid': item_data.get('startingBid'),\n 'id': item_data.get('itemData', {'id': None})['id'] or item_data.get('item', {'id': None})['id'],\n 'offers': item_data.get('offers'),\n 'currentBid': item_data.get('currentBid'),\n 'expires': item_data.get('expires'), # seconds left\n 'sellerEstablished': item_data.get('sellerEstablished'),\n 'sellerId': item_data.get('sellerId'),\n 'sellerName': item_data.get('sellerName'),\n 'watched': item_data.get('watched'),\n 'resourceId': item_data.get('resourceId'), # consumables only?\n 'discardValue': item_data.get('discardValue'), # consumables only?\n }\n if full:\n if 'itemData' in item_data:\n return_data.update({\n 'timestamp': item_data['itemData'].get('timestamp'), # auction start\n 'rating': item_data['itemData'].get('rating'),\n 'assetId': item_data['itemData'].get('assetId'),\n 'resourceId': item_data['itemData'].get('resourceId'),\n 'itemState': item_data['itemData'].get('itemState'),\n 'rareflag': item_data['itemData'].get('rareflag'),\n 'formation': item_data['itemData'].get('formation'),\n 'leagueId': item_data['itemData'].get('leagueId'),\n 'injuryType': item_data['itemData'].get('injuryType'),\n 'injuryGames': item_data['itemData'].get('injuryGames'),\n 'lastSalePrice': item_data['itemData'].get('lastSalePrice'),\n 'fitness': item_data['itemData'].get('fitness'),\n 'training': item_data['itemData'].get('training'),\n 'suspension': item_data['itemData'].get('suspension'),\n 'contract': item_data['itemData'].get('contract'),\n 'position': item_data['itemData'].get('preferredPosition'),\n 'playStyle': item_data['itemData'].get('playStyle'), # used only for players\n 'discardValue': item_data['itemData'].get('discardValue'),\n 'itemType': item_data['itemData'].get('itemType'),\n 'cardType': item_data['itemData'].get('cardsubtypeid'), # alias\n 'cardsubtypeid': item_data['itemData'].get('cardsubtypeid'), # used only for cards\n 'owners': item_data['itemData'].get('owners'),\n 'untradeable': item_data['itemData'].get('untradeable'),\n 'morale': item_data['itemData'].get('morale'),\n 'statsList': item_data['itemData'].get('statsList'), # what is this?\n 'lifetimeStats': item_data['itemData'].get('lifetimeStats'),\n 'attributeList': item_data['itemData'].get('attributeList'),\n 'teamid': item_data['itemData'].get('teamid'),\n 'assists': item_data['itemData'].get('assists'),\n 'lifetimeAssists': item_data['itemData'].get('lifetimeAssists'),\n 'loyaltyBonus': item_data['itemData'].get('loyaltyBonus'),\n 'pile': item_data['itemData'].get('pile'),\n 'nation': item_data['itemData'].get('nation'), # nation_id?\n 'year': item_data['itemData'].get('resourceGameYear'), # alias\n 'resourceGameYear': item_data['itemData'].get('resourceGameYear'),\n 'marketDataMinPrice': item_data['itemData'].get('marketDataMinPrice'),\n 'marketDataMaxPrice': item_data['itemData'].get('marketDataMaxPrice'),\n 'loans': item_data.get('loans'),\n })\n elif 'item' in item_data: # consumables only (?)\n return_data.update({\n 'cardassetid': item_data['item'].get('cardassetid'),\n 'weightrare': item_data['item'].get('weightrare'),\n 'gold': item_data['item'].get('gold'),\n 'silver': item_data['item'].get('silver'),\n 'bronze': item_data['item'].get('bronze'),\n 'consumablesContractPlayer': item_data['item'].get('consumablesContractPlayer'),\n 'consumablesContractManager': item_data['item'].get('consumablesContractManager'),\n 'consumablesFormationPlayer': item_data['item'].get('consumablesFormationPlayer'),\n 'consumablesFormationManager': item_data['item'].get('consumablesFormationManager'),\n 'consumablesPosition': item_data['item'].get('consumablesPosition'),\n 'consumablesTraining': item_data['item'].get('consumablesTraining'),\n 'consumablesTrainingPlayer': item_data['item'].get('consumablesTrainingPlayer'),\n 'consumablesTrainingManager': item_data['item'].get('consumablesTrainingManager'),\n 'consumablesTrainingGk': item_data['item'].get('consumablesTrainingGk'),\n 'consumablesTrainingPlayerPlayStyle': item_data['item'].get('consumablesTrainingPlayerPlayStyle'),\n 'consumablesTrainingGkPlayStyle': item_data['item'].get('consumablesTrainingGkPlayStyle'),\n 'consumablesTrainingManagerLeagueModifier': item_data['item'].get(\n 'consumablesTrainingManagerLeagueModifier'),\n 'consumablesHealing': item_data['item'].get('consumablesHealing'),\n 'consumablesTeamTalksPlayer': item_data['item'].get('consumablesTeamTalksPlayer'),\n 'consumablesTeamTalksTeam': item_data['item'].get('consumablesTeamTalksTeam'),\n 'consumablesFitnessPlayer': item_data['item'].get('consumablesFitnessPlayer'),\n 'consumablesFitnessTeam': item_data['item'].get('consumablesFitnessTeam'),\n 'consumables': item_data['item'].get('consumables'),\n 'count': item_data.get('count'), # consumables only (?)\n 'untradeableCount': item_data.get('untradeableCount'), # consumables only (?)\n })\n\n return return_data", "response": "Parse the item data from the server and return a nice dictionary."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns all nations in dict", "response": "def nations(timeout=timeout):\n \"\"\"Return all nations in dict {id0: nation0, id1: nation1}.\n\n :params year: Year.\n \"\"\"\n rc = requests.get(messages_url, timeout=timeout)\n rc.encoding = 'utf-8' # guessing takes huge amount of cpu time\n rc = rc.text\n data = re.findall('\"search.nationName.nation([0-9]+)\": \"(.+)\"', rc)\n nations = {}\n for i in data:\n nations[int(i[0])] = i[1]\n return nations"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef players(timeout=timeout):\n rc = requests.get('{0}{1}.json'.format(card_info_url, 'players'), timeout=timeout).json()\n players = {}\n for i in rc['Players'] + rc['LegendsPlayers']:\n players[i['id']] = {'id': i['id'],\n 'firstname': i['f'],\n 'lastname': i['l'],\n 'surname': i.get('c'),\n 'rating': i['r']}\n return players", "response": "Return all players in dict"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning all playstyles in dict", "response": "def playstyles(year=2019, timeout=timeout):\n \"\"\"Return all playstyles in dict {id0: playstyle0, id1: playstyle1}.\n\n :params year: Year.\n \"\"\"\n rc = requests.get(messages_url, timeout=timeout)\n rc.encoding = 'utf-8' # guessing takes huge amount of cpu time\n rc = rc.text\n data = re.findall('\"playstyles.%s.playstyle([0-9]+)\": \"(.+)\"' % year, rc)\n playstyles = {}\n for i in data:\n playstyles[int(i[0])] = i[1]\n return playstyles"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef logout(self, save=True):\n # self.r.get('https://www.easports.com/signout', params={'ct': self._})\n # self.r.get('https://accounts.ea.com/connect/clearsid', params={'ct': self._})\n # self.r.get('https://beta.www.origin.com/views/logout.html', params={'ct': self._})\n # self.r.get('https://help.ea.com/community/logout/', params={'ct': self._})\n self.r.delete('https://%s/ut/auth' % self.fut_host, timeout=self.timeout)\n if save:\n self.saveSession()\n # needed? https://accounts.ea.com/connect/logout?client_id=FIFA-18-WEBCLIENT&redirect_uri=https://www.easports.com/fifa/ultimate-team/web-app/auth.html\n return True", "response": "Log out nicely (like clicking on logout button).\n\n :params save: False if You don't want to save cookies."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns all playstyles in dict", "response": "def playstyles(self, year=2019):\n \"\"\"Return all playstyles in dict {id0: playstyle0, id1: playstyle1}.\n\n :params year: Year.\n \"\"\"\n if not self._playstyles:\n self._playstyles = playstyles()\n return self._playstyles"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning all leagues in a given year.", "response": "def leagues(self, year=2019):\n \"\"\"Return all leagues in dict {id0: league0, id1: league1}.\n\n :params year: Year.\n \"\"\"\n if year not in self._leagues:\n self._leagues[year] = leagues(year)\n return self._leagues[year]"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning all teams in a given year.", "response": "def teams(self, year=2019):\n \"\"\"Return all teams in dict {id0: team0, id1: team1}.\n\n :params year: Year.\n \"\"\"\n if year not in self._teams:\n self._teams[year] = teams(year)\n return self._teams[year]"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsaving cookies and session.", "response": "def saveSession(self):\n \"\"\"Save cookies/session.\"\"\"\n if self.cookies_file:\n self.r.cookies.save(ignore_discard=True)\n with open(self.token_file, 'w') as f:\n f.write('%s %s' % (self.token_type, self.access_token))"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning card info. :params resource_id: Resource id.", "response": "def cardInfo(self, resource_id):\n \"\"\"Return card info.\n\n :params resource_id: Resource id.\n \"\"\"\n # TODO: add referer to headers (futweb)\n base_id = baseId(resource_id)\n if base_id in self.players:\n return self.players[base_id]\n else: # not a player?\n url = '{0}{1}.json'.format(card_info_url, base_id)\n return requests.get(url, timeout=self.timeout).json()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nsearch for variations of the given asset id.", "response": "def searchDefinition(self, asset_id, start=0, page_size=itemsPerPage['transferMarket'], count=None):\n \"\"\"Return variations of the given asset id, e.g. IF cards.\n\n :param asset_id: Asset id / Definition id.\n :param start: (optional) Start page.\n :param count: (optional) Number of definitions you want to request.\n \"\"\"\n method = 'GET'\n url = 'defid'\n\n if count: # backward compatibility, will be removed in future\n page_size = count\n\n base_id = baseId(asset_id)\n if base_id not in self.players:\n raise FutError(reason='Invalid player asset/definition id.')\n\n params = {\n 'defId': base_id,\n 'start': start,\n 'type': 'player',\n 'count': page_size\n }\n\n rc = self.__request__(method, url, params=params)\n\n # try:\n # return [itemParse({'itemData': i}) for i in rc['itemData']]\n # except:\n # raise UnknownError('Invalid definition response')\n return [itemParse({'itemData': i}) for i in rc['itemData']]"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef search(self, ctype, level=None, category=None, assetId=None, defId=None,\n min_price=None, max_price=None, min_buy=None, max_buy=None,\n league=None, club=None, position=None, zone=None, nationality=None,\n rare=False, playStyle=None, start=0, page_size=itemsPerPage['transferMarket'],\n fast=False):\n \"\"\"Prepare search request, send and return parsed data as a dict.\n\n :param ctype: [development / ? / ?] Card type.\n :param level: (optional) [?/?/gold] Card level.\n :param category: (optional) [fitness/?/?] Card category.\n :param assetId: (optional) Asset id.\n :param defId: (optional) Definition id.\n :param min_price: (optional) Minimal price.\n :param max_price: (optional) Maximum price.\n :param min_buy: (optional) Minimal buy now price.\n :param max_buy: (optional) Maximum buy now price.\n :param league: (optional) League id.\n :param club: (optional) Club id.\n :param position: (optional) Position.\n :param nationality: (optional) Nation id.\n :param rare: (optional) [boolean] True for searching special cards.\n :param playStyle: (optional) Play style.\n :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n)\n :param page_size: (optional) Page size (items per page).\n \"\"\"\n # TODO: add \"search\" alias\n # TODO: generator\n method = 'GET'\n url = 'transfermarket'\n\n # pinEvents\n if start == 0:\n events = [self.pin.event('page_view', 'Hub - Transfers'), self.pin.event('page_view', 'Transfer Market Search')]\n self.pin.send(events, fast=fast)\n\n params = {\n 'start': start,\n 'num': page_size,\n 'type': ctype, # \"type\" namespace is reserved in python\n }\n if level:\n params['lev'] = level\n if category:\n params['cat'] = category\n if assetId:\n params['maskedDefId'] = assetId\n if defId:\n params['definitionId'] = defId\n if min_price:\n params['micr'] = min_price\n if max_price:\n params['macr'] = max_price\n if min_buy:\n params['minb'] = min_buy\n if max_buy:\n params['maxb'] = max_buy\n if league:\n params['leag'] = league\n if club:\n params['team'] = club\n if position:\n params['pos'] = position\n if zone:\n params['zone'] = zone\n if nationality:\n params['nat'] = nationality\n if rare:\n params['rare'] = 'SP'\n if playStyle:\n params['playStyle'] = playStyle\n\n rc = self.__request__(method, url, params=params, fast=fast)\n\n # pinEvents\n if start == 0:\n events = [self.pin.event('page_view', 'Transfer Market Results - List View'), self.pin.event('page_view', 'Item - Detail View')]\n self.pin.send(events, fast=fast)\n\n return [itemParse(i) for i in rc.get('auctionInfo', ())]", "response": "Search for a card in the specified language."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef bid(self, trade_id, bid, fast=False):\n method = 'PUT'\n url = 'trade/%s/bid' % trade_id\n\n if not fast:\n rc = self.tradeStatus(trade_id)[0]\n # don't bid if current bid is equal or greater than our max bid\n if rc['currentBid'] >= bid or self.credits < bid:\n return False # TODO: add exceptions\n data = {'bid': bid}\n try:\n rc = self.__request__(method, url, data=json.dumps(data), params={'sku_b': self.sku_b}, fast=fast)[\n 'auctionInfo'][0]\n except PermissionDenied: # too slow, somebody took it already :-(\n return False\n if rc['bidState'] == 'highest' or (\n rc['tradeState'] == 'closed' and rc['bidState'] == 'buyNow'): # checking 'tradeState' is required?\n return True\n else:\n return False", "response": "Make a bid.\n\n :params trade_id: Trade id.\n :params bid: Amount of credits You want to spend.\n :params fast: True for fastest bidding (skips trade status & credits check)."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef club(self, sort='desc', ctype='player', defId='', start=0, count=None, page_size=itemsPerPage['club'],\n level=None, category=None, assetId=None, league=None, club=None,\n position=None, zone=None, nationality=None, rare=False, playStyle=None):\n \"\"\"Return items in your club, excluding consumables.\n\n :param ctype: [development / ? / ?] Card type.\n :param level: (optional) [?/?/gold] Card level.\n :param category: (optional) [fitness/?/?] Card category.\n :param assetId: (optional) Asset id.\n :param defId: (optional) Definition id.\n :param min_price: (optional) Minimal price.\n :param max_price: (optional) Maximum price.\n :param min_buy: (optional) Minimal buy now price.\n :param max_buy: (optional) Maximum buy now price.\n :param league: (optional) League id.\n :param club: (optional) Club id.\n :param position: (optional) Position.\n :param nationality: (optional) Nation id.\n :param rare: (optional) [boolean] True for searching special cards.\n :param playStyle: (optional) Play style.\n :param start: (optional) Start page sent to server so it supposed to be 12/15, 24/30 etc. (default platform page_size*n)\n :param page_size: (optional) Page size (items per page)\n \"\"\"\n method = 'GET'\n url = 'club'\n\n if count: # backward compatibility, will be removed in future\n page_size = count\n\n params = {'sort': sort, 'type': ctype, 'defId': defId, 'start': start, 'count': page_size}\n if level:\n params['level'] = level\n if category:\n params['cat'] = category\n if assetId:\n params['maskedDefId'] = assetId\n if league:\n params['leag'] = league\n if club:\n params['team'] = club\n if position:\n params['pos'] = position\n if zone:\n params['zone'] = zone\n if nationality:\n params['nat'] = nationality\n if rare:\n params['rare'] = 'SP'\n if playStyle:\n params['playStyle'] = playStyle\n rc = self.__request__(method, url, params=params)\n\n # pinEvent\n if start == 0:\n if ctype == 'player':\n pgid = 'Club - Players - List View'\n elif ctype == 'staff':\n pgid = 'Club - Staff - List View'\n elif ctype in ('item', 'kit', 'ball', 'badge', 'stadium'):\n pgid = 'Club - Club Items - List View'\n # else: # TODO: THIS IS probably WRONG, detect all ctypes\n # pgid = 'Club - Club Items - List View'\n events = [self.pin.event('page_view', 'Hub - Club'), self.pin.event('page_view', pgid)]\n if rc['itemData']:\n events.append(self.pin.event('page_view', 'Item - Detail View'))\n self.pin.send(events)\n\n return [itemParse({'itemData': i}) for i in rc['itemData']]", "response": "Return items in your club."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef clubStaff(self):\n method = 'GET'\n url = 'club/stats/staff'\n\n rc = self.__request__(method, url)\n return rc", "response": "Return staff in your club."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning all consumables from club.", "response": "def clubConsumables(self, fast=False):\n \"\"\"Return all consumables from club.\"\"\"\n method = 'GET'\n url = 'club/consumables/development'\n\n rc = self.__request__(method, url)\n\n events = [self.pin.event('page_view', 'Hub - Club')]\n self.pin.send(events, fast=fast)\n events = [self.pin.event('page_view', 'Club - Consumables')]\n self.pin.send(events, fast=fast)\n events = [self.pin.event('page_view', 'Club - Consumables - List View')]\n self.pin.send(events, fast=fast)\n\n return [itemParse(i) for i in rc.get('itemData', ())]"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn a list of items from a user s squads.", "response": "def squad(self, squad_id=0, persona_id=None):\n \"\"\"Return a squad.\n\n :params squad_id: Squad id.\n \"\"\"\n method = 'GET'\n url = 'squad/%s/user/%s' % (squad_id, persona_id or self.persona_id)\n\n # pinEvents\n events = [self.pin.event('page_view', 'Hub - Squads')]\n self.pin.send(events)\n\n # TODO: ability to return other info than players only\n rc = self.__request__(method, url)\n\n # pinEvents\n events = [self.pin.event('page_view', 'Squad Details'), self.pin.event('page_view', 'Squads - Squad Overview')]\n self.pin.send(events)\n\n return [itemParse(i) for i in rc.get('players', ())]"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef tradeStatus(self, trade_id):\n method = 'GET'\n url = 'trade/status'\n\n if not isinstance(trade_id, (list, tuple)):\n trade_id = (trade_id,)\n trade_id = (str(i) for i in trade_id)\n params = {'tradeIds': ','.join(trade_id)} # multiple trade_ids not tested\n rc = self.__request__(method, url, params=params)\n return [itemParse(i, full=False) for i in rc['auctionInfo']]", "response": "Return trade status.\n\n :params trade_id: Trade id."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef tradepile(self):\n method = 'GET'\n url = 'tradepile'\n\n rc = self.__request__(method, url)\n\n # pinEvents\n events = [self.pin.event('page_view', 'Hub - Transfers'), self.pin.event('page_view', 'Transfer List - List View')]\n if rc.get('auctionInfo'):\n events.append(self.pin.event('page_view', 'Item - Detail View'))\n self.pin.send(events)\n\n return [itemParse(i) for i in rc.get('auctionInfo', ())]", "response": "Return items in tradepile."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nstarting auction. Returns trade_id.", "response": "def sell(self, item_id, bid, buy_now, duration=3600, fast=False):\n \"\"\"Start auction. Returns trade_id.\n\n :params item_id: Item id.\n :params bid: Stard bid.\n :params buy_now: Buy now price.\n :params duration: Auction duration in seconds (Default: 3600).\n \"\"\"\n method = 'POST'\n url = 'auctionhouse'\n\n # TODO: auto send to tradepile\n data = {'buyNowPrice': buy_now, 'startingBid': bid, 'duration': duration, 'itemData': {'id': item_id}}\n rc = self.__request__(method, url, data=json.dumps(data), params={'sku_b': self.sku_b})\n if not fast: # tradeStatus check like webapp do\n self.tradeStatus(rc['id'])\n return rc['id']"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef watchlistDelete(self, trade_id):\n method = 'DELETE'\n url = 'watchlist'\n\n if not isinstance(trade_id, (list, tuple)):\n trade_id = (trade_id,)\n trade_id = (str(i) for i in trade_id)\n params = {'tradeId': ','.join(trade_id)}\n self.__request__(method, url, params=params) # returns nothing\n return True", "response": "This method deletes cards from the watchlist."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ndelete card from tradepile.", "response": "def tradepileDelete(self, trade_id): # item_id instead of trade_id?\n \"\"\"Remove card from tradepile.\n\n :params trade_id: Trade id.\n \"\"\"\n method = 'DELETE'\n url = 'trade/%s' % trade_id\n\n self.__request__(method, url) # returns nothing\n # TODO: validate status code\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nsends to tradepile (alias for __sendToPile__). :params item_id: Item id. :params safe: (optional) False to disable tradepile free space check.", "response": "def sendToTradepile(self, item_id, safe=True):\n \"\"\"Send to tradepile (alias for __sendToPile__).\n\n :params item_id: Item id.\n :params safe: (optional) False to disable tradepile free space check.\n \"\"\"\n if safe and len(\n self.tradepile()) >= self.tradepile_size: # TODO?: optimization (don't parse items in tradepile)\n return False\n return self.__sendToPile__('trade', item_id=item_id)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nsend to watchlist. :params trade_id: Trade id.", "response": "def sendToWatchlist(self, trade_id):\n \"\"\"Send to watchlist.\n\n :params trade_id: Trade id.\n \"\"\"\n method = 'PUT'\n url = 'watchlist'\n\n data = {'auctionInfo': [{'id': trade_id}]}\n return self.__request__(method, url, data=json.dumps(data))"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nsends card FROM CLUB to first free slot in squad.", "response": "def sendToSbs(self, challenge_id, item_id):\n \"\"\"Send card FROM CLUB to first free slot in sbs squad.\"\"\"\n # TODO?: multiple item_ids\n method = 'PUT'\n url = 'sbs/challenge/%s/squad' % challenge_id\n\n squad = self.sbsSquad(challenge_id)\n players = []\n moved = False\n n = 0\n for i in squad['squad']['players']:\n if i['itemData']['id'] == item_id: # item already in sbs # TODO?: report reason\n return False\n if i['itemData']['id'] == 0 and not moved:\n i['itemData']['id'] = item_id\n moved = True\n players.append({\"index\": n,\n \"itemData\": {\"id\": i['itemData']['id'],\n \"dream\": False}})\n n += 1\n data = {'players': players}\n\n if not moved:\n return False\n else:\n self.__request__(method, url, data=json.dumps(data))\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef applyConsumable(self, item_id, resource_id):\n # TODO: catch exception when consumable is not found etc.\n # TODO: multiple players like in quickSell\n method = 'POST'\n url = 'item/resource/%s' % resource_id\n\n data = {'apply': [{'id': item_id}]}\n self.__request__(method, url, data=json.dumps(data))", "response": "Apply consumable on player."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef packs(self):\n method = 'GET'\n url = 'store/purchaseGroup/cardpack'\n\n params = {'ppInfo': True}\n return self.__request__(method, url, params=params)", "response": "List all currently available packs."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nconvert a decimal number to hexadecimal", "response": "def num2hex(self, num):\n '''\n Convert a decimal number to hexadecimal\n '''\n temp = ''\n for i in range(0, 4):\n x = self.hexChars[ ( num >> (i * 8 + 4) ) & 0x0F ]\n y = self.hexChars[ ( num >> (i * 8) ) & 0x0F ]\n temp += (x + y)\n\n return temp"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn the number of bits per pixel in a given data format.", "response": "def get_bits_per_pixel(data_format):\n \"\"\"\n Returns the number of (used) bits per pixel.\n So without padding.\n Returns None if format is not known.\n \"\"\"\n if data_format in component_8bit_formats:\n return 8\n elif data_format in component_10bit_formats:\n return 10\n elif data_format in component_12bit_formats:\n return 12\n elif data_format in component_14bit_formats:\n return 14\n elif data_format in component_16bit_formats:\n return 16\n # format not known\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef run(self):\n while self._base.is_running:\n if self._worker:\n self._worker()\n time.sleep(self._sleep_duration)", "response": "Runs the worker method."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef represent_pixel_location(self):\n if self.data is None:\n return None\n\n #\n return self._data.reshape(\n self.height + self.y_padding,\n int(self.width * self._num_components_per_pixel + self.x_padding)\n )", "response": "Return a NumPy array that represents the 2D pixel location of the original image."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef width(self):\n try:\n if self._part:\n value = self._part.width\n else:\n value = self._buffer.width\n except InvalidParameterException:\n value = self._node_map.Width.value\n return value", "response": "Returns the width of the data component in number of pixels."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef height(self):\n try:\n if self._part:\n value = self._part.height\n else:\n value = self._buffer.height\n except InvalidParameterException:\n value = self._node_map.Height.value\n return value", "response": "Returns the height of the data component in the buffer in number of pixels."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef data_format_value(self):\n try:\n if self._part:\n value = self._part.data_format\n else:\n value = self._buffer.pixel_format\n except InvalidParameterException:\n value = self._node_map.PixelFormat.value\n return value", "response": "Returns the data type of the data component as integer value."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef delivered_image_height(self):\n try:\n if self._part:\n value = self._part.delivered_image_height\n else:\n value = self._buffer.delivered_image_height\n except InvalidParameterException:\n value = 0\n return value", "response": "Returns the number of images in this data component."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning the X offset of the data in the buffer in number of pixels from the image origin to handle areas of interest.", "response": "def x_offset(self): # TODO: Check the naming convention.\n \"\"\"\n :return: The X offset of the data in the buffer in number of pixels from the image origin to handle areas of interest.\n \"\"\"\n try:\n if self._part:\n value = self._part.x_offset\n else:\n value = self._buffer.offset_x\n except InvalidParameterException:\n value = self._node_map.OffsetX.value\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef y_offset(self):\n try:\n if self._part:\n value = self._part.y_offset\n else:\n value = self._buffer.offset_y\n except InvalidParameterException:\n value = self._node_map.OffsetY.value\n return value", "response": "Returns the Y offset of the data in the buffer in number of pixels from the image origin to handle areas of interest."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning the X padding of the data component in the buffer in number of pixels.", "response": "def x_padding(self):\n \"\"\"\n Returns\n :return: The X padding of the data component in the buffer in number of pixels.\n \"\"\"\n try:\n if self._part:\n value = self._part.x_padding\n else:\n value = self._buffer.padding_x\n except InvalidParameterException:\n value = 0\n return value"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef queue(self):\n #\n if _is_logging_buffer_manipulation:\n self._logger.debug(\n 'Queued Buffer module #{0}'\n ' containing frame #{1}'\n ' to DataStream module {2}'\n ' of Device module {3}'\n '.'.format(\n self._buffer.context,\n self._buffer.frame_id,\n self._buffer.parent.id_,\n self._buffer.parent.parent.id_\n )\n )\n\n self._buffer.parent.queue_buffer(self._buffer)", "response": "Queues the buffer to be used for the upcoming image acquisition."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nstart image acquisition. :return: None.", "response": "def start_image_acquisition(self):\n \"\"\"\n Starts image acquisition.\n\n :return: None.\n \"\"\"\n if not self._create_ds_at_connection:\n self._setup_data_streams()\n\n #\n num_required_buffers = self._num_buffers\n for data_stream in self._data_streams:\n try:\n num_buffers = data_stream.buffer_announce_min\n if num_buffers < num_required_buffers:\n num_buffers = num_required_buffers\n except InvalidParameterException as e:\n num_buffers = num_required_buffers\n self._logger.debug(e, exc_info=True)\n\n if data_stream.defines_payload_size():\n buffer_size = data_stream.payload_size\n else:\n buffer_size = self.device.node_map.PayloadSize.value\n\n raw_buffers = self._create_raw_buffers(\n num_buffers, buffer_size\n )\n\n buffer_tokens = self._create_buffer_tokens(\n raw_buffers\n )\n\n self._announced_buffers = self._announce_buffers(\n data_stream=data_stream, _buffer_tokens=buffer_tokens\n )\n\n self._queue_announced_buffers(\n data_stream=data_stream, buffers=self._announced_buffers\n )\n\n # Reset the number of images to acquire.\n try:\n acq_mode = self.device.node_map.AcquisitionMode.value\n if acq_mode == 'Continuous':\n num_images_to_acquire = -1\n elif acq_mode == 'SingleFrame':\n num_images_to_acquire = 1\n elif acq_mode == 'MultiFrame':\n num_images_to_acquire = self.device.node_map.AcquisitionFrameCount.value\n else:\n num_images_to_acquire = -1\n except LogicalErrorException as e:\n # The node doesn't exist.\n num_images_to_acquire = -1\n self._logger.debug(e, exc_info=True)\n\n self._num_images_to_acquire = num_images_to_acquire\n\n try:\n # We're ready to start image acquisition. Lock the device's\n # transport layer related features:\n self.device.node_map.TLParamsLocked.value = 1\n except LogicalErrorException:\n # SFNC < 2.0\n pass\n\n # Start image acquisition.\n self._is_acquiring_images = True\n\n for data_stream in self._data_streams:\n data_stream.start_acquisition(\n ACQ_START_FLAGS_LIST.ACQ_START_FLAGS_DEFAULT,\n self._num_images_to_acquire\n )\n\n #\n if self.thread_image_acquisition:\n self.thread_image_acquisition.start()\n\n #\n self.device.node_map.AcquisitionStart.execute()\n\n self._logger.info(\n '{0} started image acquisition.'.format(self._device.id_)\n )\n\n if self._profiler:\n self._profiler.print_diff()"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef fetch_buffer(self, *, timeout=0, is_raw=False):\n if not self.is_acquiring_images:\n raise TimeoutException\n\n watch_timeout = True if timeout > 0 else False\n buffer = None\n base = time.time()\n\n while buffer is None:\n if watch_timeout and (time.time() - base) > timeout:\n raise TimeoutException\n else:\n with MutexLocker(self.thread_image_acquisition):\n if len(self._holding_filled_buffers) > 0:\n if is_raw:\n buffer = self._holding_filled_buffers.pop(0)\n else:\n # Update the chunk data:\n _buffer = self._holding_filled_buffers.pop(0)\n self._update_chunk_data(buffer=_buffer)\n #\n buffer = Buffer(\n buffer=_buffer,\n node_map=self.device.node_map,\n logger=self._logger\n )\n\n if _is_logging_buffer_manipulation:\n self._logger.debug(\n 'Fetched Buffer module #{0}'\n ' containing frame #{1}'\n ' of DataStream module {2}'\n ' of Device module {2}'\n '.'.format(\n buffer._buffer.context,\n buffer._buffer.frame_id,\n buffer._buffer.parent.id_,\n buffer._buffer.parent.parent.id_\n )\n )\n\n return buffer", "response": "Fetch the latest GenTL Buffer module and return it."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef stop_image_acquisition(self):\n if self.is_acquiring_images:\n #\n self._is_acquiring_images = False\n\n #\n if self.thread_image_acquisition.is_running: # TODO\n self.thread_image_acquisition.stop()\n\n with MutexLocker(self.thread_image_acquisition):\n #\n self.device.node_map.AcquisitionStop.execute()\n\n try:\n # Unlock TLParamsLocked in order to allow full device\n # configuration:\n self.device.node_map.TLParamsLocked.value = 0\n except LogicalErrorException:\n # SFNC < 2.0\n pass\n\n for data_stream in self._data_streams:\n # Stop image acquisition.\n try:\n data_stream.stop_acquisition(\n ACQ_STOP_FLAGS_LIST.ACQ_STOP_FLAGS_KILL\n )\n except (ResourceInUseException, TimeoutException) as e:\n self._logger.error(e, exc_info=True)\n\n # Flash the queue for image acquisition process.\n data_stream.flush_buffer_queue(\n ACQ_QUEUE_TYPE_LIST.ACQ_QUEUE_ALL_DISCARD\n )\n\n for event_manager in self._event_new_buffer_managers:\n event_manager.flush_event_queue()\n\n if self._create_ds_at_connection:\n self._release_buffers()\n else:\n self._release_data_streams()\n\n #\n self._has_acquired_1st_image = False\n\n #\n self._chunk_adapter.detach_buffer()\n\n #\n self._logger.info(\n '{0} stopped image acquisition.'.format(self._device.id_)\n )\n\n if self._profiler:\n self._profiler.print_diff()", "response": "Stops image acquisition.\n\n :return: None."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef add_cti_file(self, file_path: str):\n if not os.path.exists(file_path):\n self._logger.warning(\n 'Attempted to add {0} which does not exist.'.format(file_path)\n )\n\n if file_path not in self._cti_files:\n self._cti_files.append(file_path)\n self._logger.info(\n 'Added {0} to the CTI file list.'.format(file_path)\n )", "response": "Adds a CTI file to work with."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nremove the specified CTI file from the CTI file list.", "response": "def remove_cti_file(self, file_path: str):\n \"\"\"\n Removes the specified CTI file from the CTI file list.\n\n :param file_path: Set a file path to the target CTI file.\n\n :return: None.\n \"\"\"\n if file_path in self._cti_files:\n self._cti_files.remove(file_path)\n self._logger.info(\n 'Removed {0} from the CTI file list.'.format(file_path)\n )"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreset the Harvester object.", "response": "def _reset(self):\n \"\"\"\n Initializes the :class:`Harvester` object. Once you reset the\n :class:`Harvester` object, all allocated resources, including buffers\n and remote device, will be released.\n\n :return: None.\n \"\"\"\n #\n for ia in self._ias:\n ia._destroy()\n\n self._ias.clear()\n\n #\n self._logger.info('Started resetting the Harvester object.')\n self.remove_cti_files()\n self._release_gentl_producers()\n\n if self._profiler:\n self._profiler.print_diff()\n\n #\n self._logger.info('Completed resetting the Harvester object.')"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nupdating the device information list.", "response": "def update_device_info_list(self):\n \"\"\"\n Updates the device information list. You'll have to call this method\n every time you added CTI files or plugged/unplugged devices.\n\n :return: None.\n \"\"\"\n #\n self._release_gentl_producers()\n\n try:\n self._open_gentl_producers()\n self._open_systems()\n #\n for system in self._systems:\n #\n system.update_interface_info_list(self.timeout_for_update)\n\n #\n for i_info in system.interface_info_list:\n iface = i_info.create_interface()\n try:\n iface.open()\n except (\n NotInitializedException, ResourceInUseException,\n InvalidHandleException, InvalidHandleException,\n InvalidParameterException, AccessDeniedException,\n ) as e:\n self._logger.debug(e, exc_info=True)\n else:\n self._logger.info(\n 'Opened Interface module, {0}.'.format(iface.id_)\n )\n iface.update_device_info_list(self.timeout_for_update)\n self._interfaces.append(iface)\n for d_info in iface.device_info_list:\n self.device_info_list.append(d_info)\n\n except LoadLibraryException as e:\n self._logger.error(e, exc_info=True)\n self._has_revised_device_list = False\n else:\n self._has_revised_device_list = True\n\n #\n self._logger.info('Updated the device information list.')"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _destroy_image_acquirer(self, ia):\n\n id_ = None\n if ia.device:\n #\n ia.stop_image_acquisition()\n\n #\n ia._release_data_streams()\n\n #\n id_ = ia._device.id_\n\n #\n if ia.device.node_map:\n #\n if ia._chunk_adapter:\n ia._chunk_adapter.detach_buffer()\n ia._chunk_adapter = None\n self._logger.info(\n 'Detached a buffer from the chunk adapter of {0}.'.format(\n id_\n )\n )\n\n ia.device.node_map.disconnect()\n self._logger.info(\n 'Disconnected the port from the NodeMap of {0}.'.format(\n id_\n )\n )\n\n #\n if ia._device.is_open():\n ia._device.close()\n self._logger.info(\n 'Closed Device module, {0}.'.format(id_)\n )\n\n ia._device = None\n\n #\n if id_:\n self._logger.info(\n 'Destroyed the ImageAcquirer object which {0} '\n 'had belonged to.'.format(id_)\n )\n else:\n self._logger.info(\n 'Destroyed an ImageAcquirer.'\n )\n\n if self._profiler:\n self._profiler.print_diff()\n\n self._ias.remove(ia)", "response": "Destroys the ImageAcquirer object."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn a truth value for a proposition : the program is running on macOS machine.", "response": "def is_running_on_macos():\n \"\"\"\n Returns a truth value for a proposition: \"the program is running on a\n macOS machine\".\n\n :rtype: bool\n \"\"\"\n pattern = re.compile('darwin', re.IGNORECASE)\n return False if not pattern.search(platform.platform()) else True"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_sha1_signature(token, timestamp, nonce, encrypt):\n\n try:\n sortlist = [token, timestamp, nonce, to_binary(encrypt)]\n sortlist.sort()\n sha = hashlib.sha1()\n sha.update(to_binary(\"\").join(sortlist))\n return sha.hexdigest()\n except Exception as e:\n raise CryptoComputeSignatureError(e)", "response": "Returns the SHA1 signature of the token."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef login(self, verify_code=''):\n url = 'https://mp.weixin.qq.com/cgi-bin/login'\n payload = {\n 'username': self.__username,\n 'pwd': self.__password,\n 'imgcode': verify_code,\n 'f': 'json',\n }\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN',\n 'Cookie': self.__cookies,\n }\n r = requests.post(url, data=payload, headers=headers)\n\n s = re.search(r'token=(\\d+)', r.text)\n if not s:\n try:\n error_code = json.loads(r.text)['base_resp']['ret']\n except (KeyError, ValueError):\n raise LoginError(r.text)\n\n if error_code in [-8, -27]:\n raise LoginVerifyCodeError(r.text)\n elif re.search(r'readtemplate', r.text):\n raise LoginError('You need to turn off the safety protection of wechat.')\n else:\n raise LoginError(r.text)\n self.__token = int(s.group(1))\n\n self.__cookies = ''\n for cookie in r.cookies:\n self.__cookies += cookie.name + '=' + cookie.value + ';'", "response": "\u767b\u5f55\u5fae\u4fe1\u516c\u4f17\u5e73\u53f0\n \u6ce8\u610f\u5728\u5b9e\u4f8b\u5316 ``WechatExt`` \u7684\u65f6\u5019\uff0c\u5982\u679c\u6ca1\u6709\u4f20\u5165 ``token`` \u53ca ``cookies`` \uff0c\u5c06\u4f1a\u81ea\u52a8\u8c03\u7528\u8be5\u65b9\u6cd5\uff0c\u65e0\u9700\u624b\u52a8\u8c03\u7528\n \u5f53\u4e14\u4ec5\u5f53\u6355\u83b7\u5230 ``NeedLoginError`` \u5f02\u5e38\u65f6\u624d\u9700\u8981\u8c03\u7528\u6b64\u65b9\u6cd5\u8fdb\u884c\u767b\u5f55\u91cd\u8bd5\n :param verify_code: \u9a8c\u8bc1\u7801, \u4e0d\u4f20\u5165\u5219\u4e3a\u65e0\u9a8c\u8bc1\u7801\n :raises LoginVerifyCodeError: \u9700\u8981\u9a8c\u8bc1\u7801\u6216\u9a8c\u8bc1\u7801\u51fa\u9519\uff0c\u8be5\u5f02\u5e38\u4e3a ``LoginError`` \u7684\u5b50\u7c7b\n :raises LoginError: \u767b\u5f55\u51fa\u9519\u5f02\u5e38\uff0c\u5f02\u5e38\u5185\u5bb9\u4e3a\u5fae\u4fe1\u670d\u52a1\u5668\u54cd\u5e94\u7684\u5185\u5bb9\uff0c\u53ef\u4f5c\u4e3a\u65e5\u5fd7\u8bb0\u5f55\u4e0b\u6765"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_verify_code(self, file_path):\n url = 'https://mp.weixin.qq.com/cgi-bin/verifycode'\n payload = {\n 'username': self.__username,\n 'r': int(random.random() * 10000000000000),\n }\n headers = {\n 'referer': 'https://mp.weixin.qq.com/',\n }\n r = requests.get(url, data=payload, headers=headers, stream=True)\n\n self.__cookies = ''\n for cookie in r.cookies:\n self.__cookies += cookie.name + '=' + cookie.value + ';'\n\n with open(file_path, 'wb') as fd:\n for chunk in r.iter_content(1024):\n fd.write(chunk)", "response": "Get verify code from URL."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nsend a message to the specified fake.", "response": "def send_message(self, fakeid, content):\n \"\"\"\n \u4e3b\u52a8\u53d1\u9001\u6587\u672c\u6d88\u606f\n :param fakeid: \u7528\u6237\u7684 UID (\u5373 fakeid )\n :param content: \u53d1\u9001\u7684\u5185\u5bb9\n :raises NeedLoginError: \u64cd\u4f5c\u672a\u6267\u884c\u6210\u529f, \u9700\u8981\u518d\u6b21\u5c1d\u8bd5\u767b\u5f55, \u5f02\u5e38\u5185\u5bb9\u4e3a\u670d\u52a1\u5668\u8fd4\u56de\u7684\u9519\u8bef\u6570\u636e\n :raises ValueError: \u53c2\u6570\u51fa\u9519, \u5177\u4f53\u5185\u5bb9\u6709 ``fake id not exist``\n \"\"\"\n url = 'https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response'\n payload = {\n 'tofakeid': fakeid,\n 'type': 1,\n 'token': self.__token,\n 'content': content,\n 'ajax': 1,\n }\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&tofakeid={fakeid}&token={token}&lang=zh_CN'.format(\n fakeid=fakeid,\n token=self.__token,\n ),\n 'cookie': self.__cookies,\n }\n r = requests.post(url, data=payload, headers=headers)\n\n try:\n message = json.loads(r.text)\n except ValueError:\n raise NeedLoginError(r.text)\n try:\n if message['base_resp']['ret'] == -21:\n raise ValueError('fake id not exist')\n if message['base_resp']['ret'] != 0:\n raise NeedLoginError(r.text)\n except KeyError:\n raise NeedLoginError(r.text)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef stat_article_detail_list(self, page=1, start_date=str(date.today()+timedelta(days=-30)), end_date=str(date.today())):\n self._init_plugin_token_appid()\n\n url = 'http://mta.qq.com/mta/wechat/ctr_article_detail/get_list?sort=RefDate%20desc&keyword=&page={page}&appid={appid}&pluginid=luopan&token={token}&from=&src=false&devtype=3&time_type=day&start_date={start_date}&end_date={end_date}&need_compare=0&app_id=&rnd={rnd}&ajax=1'.format(\n page=page,\n appid=self.__appid,\n token=self.__plugin_token,\n rnd=int(time.time()),\n start_date=start_date,\n end_date=end_date,\n )\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'http://mta.qq.com/mta/wechat/ctr_article_detail/get_list?sort=RefDate%20desc&keyword=&page={page}&appid={appid}&pluginid=luopan&token={token}&from=&src=false&devtype=3&time_type=day&start_date={start_date}&end_date={end_date}&need_compare=0&app_id=&rnd={rnd}&ajax=1'.format(\n page=page,\n appid=self.__appid,\n token=self.__plugin_token,\n rnd=int(time.time()),\n start_date=start_date,\n end_date=end_date,\n ),\n 'cookie': self.__cookies,\n }\n r = requests.get(url, headers=headers)\n\n if not re.search(r'wechat_token', self.__cookies):\n for cookie in r.cookies:\n self.__cookies += cookie.name + '=' + cookie.value + ';'\n\n try:\n data = json.loads(r.text)\n if data.get('is_session_expire'):\n raise NeedLoginError(r.text)\n message = json.dumps(data, ensure_ascii=False)\n except (KeyError, ValueError):\n raise NeedLoginError(r.text)\n\n return message", "response": "stat_article_detail_list - Return a JSON representation of the article."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngetting a list of all groups.", "response": "def get_group_list(self):\n \"\"\"\n \u83b7\u53d6\u5206\u7ec4\u5217\u8868\n\n \u8fd4\u56deJSON\u793a\u4f8b::\n\n {\n \"groups\": [\n {\n \"cnt\": 8,\n \"id\": 0,\n \"name\": \"\u672a\u5206\u7ec4\"\n },\n {\n \"cnt\": 0,\n \"id\": 1,\n \"name\": \"\u9ed1\u540d\u5355\"\n },\n {\n \"cnt\": 0,\n \"id\": 2,\n \"name\": \"\u661f\u6807\u7ec4\"\n }\n ]\n }\n\n :return: \u8fd4\u56de\u7684 JSON \u6570\u636e\n :raises NeedLoginError: \u64cd\u4f5c\u672a\u6267\u884c\u6210\u529f, \u9700\u8981\u518d\u6b21\u5c1d\u8bd5\u767b\u5f55, \u5f02\u5e38\u5185\u5bb9\u4e3a\u670d\u52a1\u5668\u8fd4\u56de\u7684\u9519\u8bef\u6570\u636e\n \"\"\"\n url = 'https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=0&lang=zh_CN&f=json&token={token}'.format(\n token=self.__token,\n )\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&pagesize=10&pageidx=0&type=0&groupid=0&lang=zh_CN&token='.format(\n token=self.__token,\n ),\n 'cookie': self.__cookies,\n }\n r = requests.get(url, headers=headers)\n\n try:\n message = json.loads(r.text)['group_list']\n except (KeyError, ValueError):\n raise NeedLoginError(r.text)\n\n return message"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef send_news(self, fakeid, msgid):\n url = 'https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response'\n payload = {\n 'lang': 'zh_CN',\n 'f': 'json',\n 'tofakeid': fakeid,\n 'type': 10,\n 'token': self.__token,\n 'appmsgid': msgid,\n 'app_id': msgid,\n 'error': 'false',\n 'ajax': 1,\n 'random': random.random(),\n }\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com/cgi-bin/singlemsgpage?fromfakeid={fakeid}&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN'.format(\n fakeid=fakeid,\n ),\n 'cookie': self.__cookies,\n }\n r = requests.post(url, data=payload, headers=headers)\n\n try:\n message = json.loads(r.text)\n except ValueError:\n raise NeedLoginError(r.text)\n try:\n if message['base_resp']['ret'] == 10700 or message['base_resp']['ret'] == -21:\n raise ValueError('fake id not exist')\n if message['base_resp']['ret'] == 10705:\n raise ValueError('message id not exist')\n if message['base_resp']['ret'] != 0:\n raise NeedLoginError(r.text)\n except KeyError:\n raise NeedLoginError(r.text)", "response": "Send news to a fake."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nuploads a file to the Music Store.", "response": "def upload_file(self, filepath):\n \"\"\"\n \u4e0a\u4f20\u7d20\u6750 (\u56fe\u7247/\u97f3\u9891/\u89c6\u9891)\n :param filepath: \u672c\u5730\u6587\u4ef6\u8def\u5f84\n :return: \u76f4\u63a5\u8fd4\u56de\u4e0a\u4f20\u540e\u7684\u6587\u4ef6 ID (fid)\n :raises NeedLoginError: \u64cd\u4f5c\u672a\u6267\u884c\u6210\u529f, \u9700\u8981\u518d\u6b21\u5c1d\u8bd5\u767b\u5f55, \u5f02\u5e38\u5185\u5bb9\u4e3a\u670d\u52a1\u5668\u8fd4\u56de\u7684\u9519\u8bef\u6570\u636e\n :raises ValueError: \u53c2\u6570\u51fa\u9519, \u9519\u8bef\u539f\u56e0\u76f4\u63a5\u6253\u5370\u5f02\u5e38\u5373\u53ef (\u5e38\u89c1\u9519\u8bef\u5185\u5bb9: ``file not exist``: \u627e\u4e0d\u5230\u672c\u5730\u6587\u4ef6, ``audio too long``: \u97f3\u9891\u6587\u4ef6\u8fc7\u957f, ``file invalid type``: \u6587\u4ef6\u683c\u5f0f\u4e0d\u6b63\u786e, \u8fd8\u6709\u5176\u4ed6\u9519\u8bef\u8bf7\u81ea\u884c\u68c0\u67e5)\n \"\"\"\n self._init_ticket()\n\n url = 'https://mp.weixin.qq.com/cgi-bin/filetransfer?action=upload_material&f=json&ticket_id={ticket_id}&ticket={ticket}&token={token}&lang=zh_CN'.format(\n ticket_id=self.__ticket_id,\n ticket=self.__ticket,\n token=self.__token,\n )\n try:\n files = {'file': open(filepath, 'rb')}\n except IOError:\n raise ValueError('file not exist')\n payloads = {\n 'Filename': filepath,\n 'folder': '/cgi-bin/uploads',\n 'Upload': 'Submit Query',\n }\n headers = {\n 'referer': 'http://mp.weixin.qq.com/cgi-bin/indexpage?t=wxm-upload&lang=zh_CN&type=2&formId=1',\n 'cookie': self.__cookies,\n }\n r = requests.post(url, files=files, data=payloads, headers=headers)\n\n try:\n message = json.loads(r.text)\n except ValueError:\n raise NeedLoginError(r.text)\n try:\n if message['base_resp']['ret'] != 0:\n raise ValueError(message['base_resp']['err_msg'])\n except KeyError:\n raise NeedLoginError(r.text)\n\n return message['content']"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef send_file(self, fakeid, fid, type):\n if type == 4: # \u6b64\u5904\u5224\u65ad\u4e3a\u517c\u5bb9\u5386\u53f2\u7248\u672c, \u5fae\u4fe1\u5b98\u65b9\u5df2\u7ecf\u5c06\u89c6\u9891\u7c7b\u578b\u4fee\u6539\u4e3a 15\n type = 15\n\n url = 'https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&f=json&token={token}&lang=zh_CN'.format(\n token=self.__token,\n )\n payloads = {}\n if type == 2 or type == 3: # \u5982\u679c\u6587\u4ef6\u7c7b\u578b\u662f\u56fe\u7247\u6216\u8005\u97f3\u9891\n payloads = {\n 'token': self.__token,\n 'lang': 'zh_CN',\n 'f': 'json',\n 'ajax': 1,\n 'random': random.random(),\n 'type': type,\n 'file_id': fid,\n 'tofakeid': fakeid,\n 'fileid': fid,\n 'imgcode': '',\n }\n elif type == 15: # \u5982\u679c\u6587\u4ef6\u7c7b\u578b\u662f\u89c6\u9891\n payloads = {\n 'token': self.__token,\n 'lang': 'zh_CN',\n 'f': 'json',\n 'ajax': 1,\n 'random': random.random(),\n 'type': type,\n 'app_id': fid,\n 'tofakeid': fakeid,\n 'appmsgid': fid,\n 'imgcode': '',\n }\n headers = {\n 'referer': 'https://mp.weixin.qq.com/cgi-bin/singlesendpage?tofakeid={fakeid}&t=message/send&action=index&token={token}&lang=zh_CN'.format(\n fakeid=fakeid,\n token=self.__token,\n ),\n 'cookie': self.__cookies,\n 'x-requested-with': 'XMLHttpRequest',\n }\n r = requests.post(url, data=payloads, headers=headers)\n\n try:\n message = json.loads(r.text)\n except ValueError:\n raise NeedLoginError(r.text)\n try:\n if message['base_resp']['ret'] != 0:\n raise ValueError(message['base_resp']['err_msg'])\n except KeyError:\n raise NeedLoginError(r.text)", "response": "send_file - Sends a file to a fakeid"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get_avatar(self, fakeid):\n url = 'https://mp.weixin.qq.com/misc/getheadimg?fakeid={fakeid}&token={token}&lang=zh_CN'.format(\n fakeid=fakeid,\n token=self.__token,\n )\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com/cgi-bin/getmessage?t=wxm-message&lang=zh_CN&count=50&token={token}'.format(\n token=self.__token,\n ),\n 'cookie': self.__cookies,\n }\n r = requests.get(url, headers=headers, stream=True)\n\n return r.raw.data", "response": "get avatar from JPG"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_new_message_num(self, lastid=0):\n url = 'https://mp.weixin.qq.com/cgi-bin/getnewmsgnum?f=json&t=ajax-getmsgnum&lastmsgid={lastid}&token={token}&lang=zh_CN'.format(\n lastid=lastid,\n token=self.__token,\n )\n payloads = {\n 'ajax': 1,\n 'f': 'json',\n 'random': random.random(),\n 'lang': 'zh_CN',\n 'token': self.__token,\n }\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token={token}&lang=zh_CN'.format(\n token=self.__token,\n ),\n 'cookie': self.__cookies,\n }\n r = requests.get(url, data=payloads, headers=headers)\n\n try:\n return int(json.loads(r.text)['newTotalMsgCount'])\n except (KeyError, ValueError):\n raise NeedLoginError(r.text)", "response": "Get new message number."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef get_message_list(self, lastid=0, offset=0, count=20, day=7, star=False):\n if star:\n star_param = '&action=star'\n else:\n star_param = ''\n if lastid == 0:\n lastid = ''\n\n url = 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&f=json&lang=zh_CN{star}&count={count}&day={day}&frommsgid={lastid}&offset={offset}&token={token}'.format(\n star=star_param,\n count=count,\n day=day,\n lastid=lastid,\n offset=offset,\n token=self.__token,\n )\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token={token}&lang=zh_CN'.format(token=self.__token),\n 'cookie': self.__cookies,\n }\n r = requests.get(url, headers=headers)\n\n try:\n message = json.loads(r.text)['msg_items']\n except (KeyError, ValueError):\n raise NeedLoginError(r.text)\n\n return message", "response": "get_message_list - Returns a list of message objects"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngetting a message from MP3", "response": "def get_message_voice(self, msgid):\n \"\"\"\n \u6839\u636e\u6d88\u606f ID \u83b7\u53d6\u8bed\u97f3\u6d88\u606f\u5185\u5bb9\n :param msgid: \u6d88\u606f ID\n :return: \u4e8c\u8fdb\u5236 MP3 \u97f3\u9891\u5b57\u7b26\u4e32, \u53ef\u76f4\u63a5\u4f5c\u4e3a File Object \u4e2d write \u7684\u53c2\u6570\n :raises NeedLoginError: \u64cd\u4f5c\u672a\u6267\u884c\u6210\u529f, \u9700\u8981\u518d\u6b21\u5c1d\u8bd5\u767b\u5f55, \u5f02\u5e38\u5185\u5bb9\u4e3a\u670d\u52a1\u5668\u8fd4\u56de\u7684\u9519\u8bef\u6570\u636e\n :raises ValueError: \u53c2\u6570\u51fa\u9519, \u9519\u8bef\u539f\u56e0\u76f4\u63a5\u6253\u5370\u5f02\u5e38\u5373\u53ef, \u9519\u8bef\u5185\u5bb9: ``voice message not exist``: msg\u53c2\u6570\u65e0\u6548\n \"\"\"\n url = 'https://mp.weixin.qq.com/cgi-bin/getvoicedata?msgid={msgid}&fileid=&token={token}&lang=zh_CN'.format(\n msgid=msgid,\n token=self.__token,\n )\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com/cgi-bin/message?t=message/list&token={token}&count=20&day=7'.format(\n token=self.__token,\n ),\n 'cookie': self.__cookies,\n }\n r = requests.get(url, headers=headers, stream=True)\n\n # \u68c0\u6d4b\u4f1a\u8bdd\u662f\u5426\u8d85\u65f6\n if r.headers.get('content-type', None) == 'text/html; charset=UTF-8':\n raise NeedLoginError(r.text)\n # \u68c0\u6d4b\u8bed\u97f3\u662f\u5426\u5b58\u5728\n if not r.raw.data:\n raise ValueError('voice message not exist')\n\n return r.raw.data"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ninitialize self - information.", "response": "def _init_self_information(self):\n \"\"\"\n \u521d\u59cb\u5316\u516c\u4f17\u53f7\u81ea\u8eab\u7684\u5c5e\u6027\u503c (\u76ee\u524d\u5305\u62ec ``Ticket`` \u503c \u53ca \u516c\u4f17\u53f7\u81ea\u8eab\u7684 ``fakeid`` \u503c)\n :raises NeedLoginError: \u64cd\u4f5c\u672a\u6267\u884c\u6210\u529f, \u9700\u8981\u518d\u6b21\u5c1d\u8bd5\u767b\u5f55, \u5f02\u5e38\u5185\u5bb9\u4e3a\u670d\u52a1\u5668\u8fd4\u56de\u7684\u9519\u8bef\u6570\u636e\n \"\"\"\n url = 'https://mp.weixin.qq.com/cgi-bin/home?t=home/index&lang=zh_CN&token={token}'.format(token=self.__token)\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com',\n 'cookie': self.__cookies,\n }\n r = requests.get(url, headers=headers)\n\n # \u83b7\u53d6 Ticket ID \u503c\n ticket_id = re.search(r'user_name:\\\"(.*)\\\"', r.text)\n if not ticket_id:\n raise NeedLoginError(r.text)\n self.__ticket_id = ticket_id.group(1)\n\n # \u83b7\u53d6 Ticket \u503c\n ticket = re.search(r'ticket:\\\"(.*)\\\"', r.text)\n if not ticket:\n raise NeedLoginError(r.text)\n self.__ticket = ticket.group(1)\n\n # \u83b7\u53d6\u516c\u4f17\u53f7\u81ea\u8eab\u7684 fakeid \u503c\n fakeid = re.search(r'uin:\\\"(.*)\\\"', r.text)\n if not fakeid:\n raise NeedLoginError(r.text)\n self.__fakeid = fakeid.group(1)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _init_plugin_token_appid(self):\n if not self.__plugin_token or not self.__appid:\n url = 'https://mp.weixin.qq.com/misc/pluginloginpage?action=stat_article_detail&pluginid=luopan&t=statistics/index&token={token}&lang=zh_CN'.format(\n token=self.__token,\n )\n headers = {\n 'x-requested-with': 'XMLHttpRequest',\n 'referer': 'https://mp.weixin.qq.com/misc/pluginloginpage?action=stat_article_detail&pluginid=luopan&t=statistics/index&token={token}&lang=zh_CN'.format(\n token=self.__token,\n ),\n 'cookie': self.__cookies,\n }\n r = requests.get(url, headers=headers)\n\n plugin_token = re.search(r\"pluginToken : '(\\S+)',\", r.text)\n if not plugin_token:\n raise NeedLoginError(r.text)\n self.__plugin_token = plugin_token.group(1)\n\n appid = re.search(r\"appid : '(\\S+)',\", r.text)\n if not appid:\n raise NeedLoginError(r.text)\n self.__appid = appid.group(1)", "response": "Init plugin token and appid"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef set_appid_appsecret(self, appid, appsecret):\n self.__appid = appid\n self.__appsecret = appsecret\n self._update_crypto()", "response": "set appid and appsecret"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef grant_jsapi_ticket(self):\n self._check_appid_appsecret()\n\n if callable(self.__jsapi_ticket_refreshfunc):\n self.__jsapi_ticket, self.__jsapi_ticket_expires_at = self.__jsapi_ticket_refreshfunc()\n return\n\n response_json = self.__request.get(\n url=\"https://api.weixin.qq.com/cgi-bin/ticket/getticket\",\n params={\n \"type\": \"jsapi\",\n },\n access_token=self.access_token,\n )\n self.__jsapi_ticket = response_json['ticket']\n self.__jsapi_ticket_expires_at = int(time.time()) + response_json['expires_in']\n\n if callable(self.__jsapi_ticket_setfunc):\n self.__jsapi_ticket_setfunc(self.__jsapi_ticket, self.__jsapi_ticket_expires_at)\n\n return response_json", "response": "\u83b7\u53d6 jsapi ticket \u5e76\u66f4\u65b0\u5f53\u524d\u914d\u7f6e\n :return: \u8fd4\u56de\u7684 JSON \u6570\u636e\u5305 (\u4f20\u5165 jsapi_ticket_refreshfunc \u53c2\u6570\u540e\u8fd4\u56de None)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _update_crypto(self):\n if self.__encrypt_mode in ['compatible', 'safe'] and self.__encoding_aes_key is not None:\n if self.__token is None or self.__appid is None:\n raise NeedParamError('Please provide token and appid parameters in the construction of class.')\n self.__crypto = BasicCrypto(self.__token, self.__encoding_aes_key, self.__appid)\n else:\n self.__crypto = None", "response": "Update the internal crypto object."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef check_signature(self, signature, timestamp, nonce):\n if not signature or not timestamp or not nonce:\n return False\n\n tmp_list = [self.conf.token, timestamp, nonce]\n tmp_list.sort()\n tmp_str = ''.join(tmp_list)\n if signature != hashlib.sha1(tmp_str.encode('utf-8')).hexdigest():\n return False\n\n return True", "response": "Check if the signature is correct."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef generate_jsapi_signature(self, timestamp, noncestr, url, jsapi_ticket=None):\n if not jsapi_ticket:\n jsapi_ticket = self.conf.jsapi_ticket\n data = {\n 'jsapi_ticket': jsapi_ticket,\n 'noncestr': noncestr,\n 'timestamp': timestamp,\n 'url': url,\n }\n keys = list(data.keys())\n keys.sort()\n data_str = '&'.join(['%s=%s' % (key, data[key]) for key in keys])\n signature = hashlib.sha1(data_str.encode('utf-8')).hexdigest()\n return signature", "response": "\u4f7f\u7528 jsapi_ticket \u5bf9 url \u8fdb\u884c\u7b7e\u540d\n :param timestamp: \u65f6\u95f4\u6233\n :param noncestr: \u968f\u673a\u6570\n :param url: \u8981\u7b7e\u540d\u7684 url\uff0c\u4e0d\u5305\u542b # \u53ca\u5176\u540e\u9762\u90e8\u5206\n :param jsapi_ticket: (\u53ef\u9009\u53c2\u6570) jsapi_ticket \u503c (\u5982\u4e0d\u63d0\u4f9b\u5c06\u81ea\u52a8\u901a\u8fc7 appid \u548c appsecret \u83b7\u53d6)\n :return: \u8fd4\u56desha1\u7b7e\u540d\u7684hexdigest\u503c"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef parse_data(self, data, msg_signature=None, timestamp=None, nonce=None):\n result = {}\n if isinstance(data, six.text_type): # unicode to str(PY2), str to bytes(PY3)\n data = data.encode('utf-8')\n\n if self.conf.encrypt_mode == 'safe':\n if not (msg_signature and timestamp and nonce):\n raise ParseError('must provide msg_signature/timestamp/nonce in safe encrypt mode')\n\n data = self.conf.crypto.decrypt_message(\n msg=data,\n msg_signature=msg_signature,\n timestamp=timestamp,\n nonce=nonce,\n )\n try:\n xml = XMLStore(xmlstring=data)\n except Exception:\n raise ParseError()\n\n result = xml.xml2dict\n result['raw'] = data\n result['type'] = result.pop('MsgType').lower()\n\n message_type = MESSAGE_TYPES.get(result['type'], UnknownMessage)\n self.__message = message_type(result)\n self.__is_parse = True", "response": "Parse the data and return a dict with the message and the message type."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef response_text(self, content, escape=False):\n self._check_parse()\n content = self._transcoding(content)\n if escape:\n if six.PY2:\n content = cgi.escape(content)\n else:\n import html\n content = html.escape(content)\n\n response = TextReply(message=self.__message, content=content).render()\n return self._encrypt_response(response)", "response": "Return a text reply"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn a response to a voice", "response": "def response_voice(self, media_id):\n \"\"\"\n \u5c06 media_id \u6240\u4ee3\u8868\u7684\u8bed\u97f3\u7ec4\u88c5\u4e3a\u7b26\u5408\u5fae\u4fe1\u670d\u52a1\u5668\u8981\u6c42\u7684\u54cd\u5e94\u6570\u636e\n :param media_id: \u8bed\u97f3\u7684 MediaID\n :return: \u7b26\u5408\u5fae\u4fe1\u670d\u52a1\u5668\u8981\u6c42\u7684 XML \u54cd\u5e94\u6570\u636e\n \"\"\"\n self._check_parse()\n\n response = VoiceReply(message=self.__message, media_id=media_id).render()\n return self._encrypt_response(response)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef response_video(self, media_id, title=None, description=None):\n self._check_parse()\n title = self._transcoding(title)\n description = self._transcoding(description)\n\n response = VideoReply(message=self.__message, media_id=media_id, title=title, description=description).render()\n return self._encrypt_response(response)", "response": "This method returns a XML response that contains a video."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef response_music(self, music_url, title=None, description=None, hq_music_url=None, thumb_media_id=None):\n self._check_parse()\n music_url = self._transcoding(music_url)\n title = self._transcoding(title)\n description = self._transcoding(description)\n hq_music_url = self._transcoding(hq_music_url)\n\n response = MusicReply(message=self.__message, title=title, description=description, music_url=music_url,\n hq_music_url=hq_music_url, thumb_media_id=thumb_media_id).render()\n return self._encrypt_response(response)", "response": "This method returns the MusicReply XML response."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef response_news(self, articles):\n self._check_parse()\n for article in articles:\n if article.get('title'):\n article['title'] = self._transcoding(article['title'])\n if article.get('description'):\n article['description'] = self._transcoding(article['description'])\n if article.get('picurl'):\n article['picurl'] = self._transcoding(article['picurl'])\n if article.get('url'):\n article['url'] = self._transcoding(article['url'])\n\n news = ArticleReply(message=self.__message)\n for article in articles:\n article = Article(**article)\n news.add_article(article)\n response = news.render()\n return self._encrypt_response(response)", "response": "\u5c06\u65b0\u95fb\u4fe1\u606f\u7ec4\u88c5\u4e3a\u7b26\u5408\u5fae\u4fe1\u670d\u52a1\u5668\u8981\u6c42\u7684\u54cd\u5e94\u6570\u636e\n :param articles: list \u5bf9\u8c61, \u6bcf\u4e2a\u5143\u7d20\u4e3a\u4e00\u4e2a dict \u5bf9\u8c61, key \u5305\u542b `title`, `description`, `picurl`, `url`\n :return: \u7b26\u5408\u5fae\u4fe1\u670d\u52a1\u5668\u8981\u6c42\u7684 XML \u54cd\u5e94\u6570\u636e"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning group transfer message.", "response": "def group_transfer_message(self):\n \"\"\"\n \u5c06 message \u7fa4\u53d1\u5230\u591a\u5ba2\u670d\u7cfb\u7edf\n :return: \u7b26\u5408\u5fae\u4fe1\u670d\u52a1\u5668\u8981\u6c42\u7684 XML \u54cd\u5e94\u6570\u636e\n \"\"\"\n self._check_parse()\n response = GroupTransferReply(message=self.__message).render()\n return self._encrypt_response(response)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncreates a new menu", "response": "def create_menu(self, menu_data):\n \"\"\"\n \u521b\u5efa\u81ea\u5b9a\u4e49\u83dc\u5355 ::\n\n # -*- coding: utf-8 -*-\n wechat = WechatBasic(appid='appid', appsecret='appsecret')\n wechat.create_menu({\n 'button':[\n {\n 'type': 'click',\n 'name': '\u4eca\u65e5\u6b4c\u66f2',\n 'key': 'V1001_TODAY_MUSIC'\n },\n {\n 'type': 'click',\n 'name': '\u6b4c\u624b\u7b80\u4ecb',\n 'key': 'V1001_TODAY_SINGER'\n },\n {\n 'name': '\u83dc\u5355',\n 'sub_button': [\n {\n 'type': 'view',\n 'name': '\u641c\u7d22',\n 'url': 'http://www.soso.com/'\n },\n {\n 'type': 'view',\n 'name': '\u89c6\u9891',\n 'url': 'http://v.qq.com/'\n },\n {\n 'type': 'click',\n 'name': '\u8d5e\u4e00\u4e0b\u6211\u4eec',\n 'key': 'V1001_GOOD'\n }\n ]\n }\n ]})\n\n \u8be6\u60c5\u8bf7\u53c2\u8003 http://mp.weixin.qq.com/wiki/13/43de8269be54a0a6f64413e4dfa94f39.html\n :param menu_data: Python \u5b57\u5178\n :return: \u8fd4\u56de\u7684 JSON \u6570\u636e\u5305\n \"\"\"\n menu_data = self._transcoding_dict(menu_data)\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/menu/create',\n data=menu_data\n )"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef upload_media(self, media_type, media_file, extension=''):\n if six.PY2:\n return self._upload_media_py2(media_type, media_file, extension)\n else:\n return self._upload_media_py3(media_type, media_file, extension)", "response": "Upload a media to the API."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndownloading a single media from the server", "response": "def download_media(self, media_id):\n \"\"\"\n \u4e0b\u8f7d\u591a\u5a92\u4f53\u6587\u4ef6\n \u8be6\u60c5\u8bf7\u53c2\u8003 http://mp.weixin.qq.com/wiki/10/78b15308b053286e2a66b33f0f0f5fb6.html\n :param media_id: \u5a92\u4f53\u6587\u4ef6 ID\n :return: requests \u7684 Response \u5b9e\u4f8b\n \"\"\"\n return self.request.get(\n 'https://api.weixin.qq.com/cgi-bin/media/get',\n params={\n 'media_id': media_id,\n },\n stream=True,\n )"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef move_user(self, user_id, group_id):\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/groups/members/update',\n data={\n 'openid': user_id,\n 'to_groupid': group_id,\n }\n )", "response": "Move user to group"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_user_info(self, user_id, lang='zh_CN'):\n return self.request.get(\n url='https://api.weixin.qq.com/cgi-bin/user/info',\n params={\n 'openid': user_id,\n 'lang': lang,\n }\n )", "response": "\u83b7\u53d6\u7528\u6237\u57fa\u672c\u4fe1\u606f\n \u8be6\u60c5\u8bf7\u53c2\u8003 http://mp.weixin.qq.com/wiki/14/bb5031008f1494a59c6f71fa0f319c66.html\n :param user_id: \u7528\u6237 ID, \u5c31\u662f\u4f60\u6536\u5230\u7684 WechatMessage \u7684 source\n :param lang: \u8fd4\u56de\u56fd\u5bb6\u5730\u533a\u8bed\u8a00\u7248\u672c\uff0czh_CN \u7b80\u4f53\uff0czh_TW \u7e41\u4f53\uff0cen \u82f1\u8bed\n :return: \u8fd4\u56de\u7684 JSON \u6570\u636e\u5305"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting the list of followers.", "response": "def get_followers(self, first_user_id=None):\n \"\"\"\n \u83b7\u53d6\u5173\u6ce8\u8005\u5217\u8868\n \u8be6\u60c5\u8bf7\u53c2\u8003 http://mp.weixin.qq.com/wiki/3/17e6919a39c1c53555185907acf70093.html\n :param first_user_id: \u53ef\u9009\u3002\u7b2c\u4e00\u4e2a\u62c9\u53d6\u7684OPENID\uff0c\u4e0d\u586b\u9ed8\u8ba4\u4ece\u5934\u5f00\u59cb\u62c9\u53d6\n :return: \u8fd4\u56de\u7684 JSON \u6570\u636e\u5305\n \"\"\"\n params = dict()\n if first_user_id:\n params['next_openid'] = first_user_id\n return self.request.get('https://api.weixin.qq.com/cgi-bin/user/get', params=params)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef send_text_message(self, user_id, content):\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/message/custom/send',\n data={\n 'touser': user_id,\n 'msgtype': 'text',\n 'text': {\n 'content': content,\n },\n }\n )", "response": "Send a text message to a user"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef send_image_message(self, user_id, media_id):\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/message/custom/send',\n data={\n 'touser': user_id,\n 'msgtype': 'image',\n 'image': {\n 'media_id': media_id,\n },\n }\n )", "response": "Send an image message to the user."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef send_voice_message(self, user_id, media_id):\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/message/custom/send',\n data={\n 'touser': user_id,\n 'msgtype': 'voice',\n 'voice': {\n 'media_id': media_id,\n },\n }\n )", "response": "Send voice message to user"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nsend a video message to a user.", "response": "def send_video_message(self, user_id, media_id, title=None, description=None):\n \"\"\"\n \u53d1\u9001\u89c6\u9891\u6d88\u606f\n \u8be6\u60c5\u8bf7\u53c2\u8003 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html\n :param user_id: \u7528\u6237 ID, \u5c31\u662f\u4f60\u6536\u5230\u7684 WechatMessage \u7684 source\n :param media_id: \u53d1\u9001\u7684\u89c6\u9891\u7684\u5a92\u4f53ID\u3002 \u53ef\u4ee5\u901a\u8fc7 :func:`upload_media` \u4e0a\u4f20\u3002\n :param title: \u89c6\u9891\u6d88\u606f\u7684\u6807\u9898\n :param description: \u89c6\u9891\u6d88\u606f\u7684\u63cf\u8ff0\n :return: \u8fd4\u56de\u7684 JSON \u6570\u636e\u5305\n \"\"\"\n video_data = {\n 'media_id': media_id,\n }\n if title:\n video_data['title'] = title\n if description:\n video_data['description'] = description\n\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/message/custom/send',\n data={\n 'touser': user_id,\n 'msgtype': 'video',\n 'video': video_data,\n }\n )"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef send_article_message(self, user_id, articles=None, media_id=None):\n # neither 'articles' nor 'media_id' is specified\n if articles is None and media_id is None:\n raise TypeError('must provide one parameter in \"articles\" and \"media_id\"')\n\n # articles specified\n if articles:\n articles_data = []\n for article in articles:\n article = Article(**article)\n articles_data.append({\n 'title': article.title,\n 'description': article.description,\n 'url': article.url,\n 'picurl': article.picurl,\n })\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/message/custom/send',\n data={\n 'touser': user_id,\n 'msgtype': 'news',\n 'news': {\n 'articles': articles_data,\n },\n }\n )\n\n # media_id specified\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/message/custom/send',\n data={\n 'touser': user_id,\n 'msgtype': 'mpnews',\n 'mpnews': {\n 'media_id': media_id,\n },\n }\n )", "response": "Send article message to user"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef create_qrcode(self, data):\n data = self._transcoding_dict(data)\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/qrcode/create',\n data=data\n )", "response": "\u521b\u5efa\u4e8c\u7ef4\u7801\n \u8be6\u60c5\u8bf7\u53c2\u8003 http://mp.weixin.qq.com/wiki/18/28fc21e7ed87bec960651f0ce873ef8a.html\n :param data: \u4f60\u8981\u53d1\u9001\u7684\u53c2\u6570 dict\n :return: \u8fd4\u56de\u7684 JSON \u6570\u636e\u5305"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngetting the ID of a specific template.", "response": "def get_template_id(self, template_id_short):\n \"\"\"\n \u83b7\u5f97\u6a21\u677fID\n \u8be6\u60c5\u8bf7\u53c2\u8003 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html\n :param template_id_short: \u6a21\u677f\u5e93\u4e2d\u6a21\u677f\u7684\u7f16\u53f7\uff0c\u6709\u201cTM**\u201d\u548c\u201cOPENTMTM**\u201d\u7b49\u5f62\u5f0f\n :return: \u8fd4\u56de\u7684 JSON \u6570\u636e\u5305\n \"\"\"\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/template/api_add_template',\n data={\n 'template_id_short': str(template_id_short),\n }\n )"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nsend a template message to a user.", "response": "def send_template_message(self, user_id, template_id, data, url='', topcolor='#FF0000'):\n \"\"\"\n \u53d1\u9001\u6a21\u7248\u6d88\u606f\n \u8be6\u60c5\u8bf7\u53c2\u8003 http://mp.weixin.qq.com/wiki/17/304c1885ea66dbedf7dc170d84999a9d.html\n :param user_id: \u7528\u6237 ID, \u5c31\u662f\u4f60\u6536\u5230\u7684 WechatMessage \u7684 source (OpenID)\n :param template_id: \u6a21\u677fID\n :param data: \u6a21\u677f\u6d88\u606f\u6570\u636e (dict\u5f62\u5f0f)\uff0c\u793a\u4f8b\u5982\u4e0b\uff1a\n {\n \"first\": {\n \"value\": \"\u606d\u559c\u4f60\u8d2d\u4e70\u6210\u529f\uff01\",\n \"color\": \"#173177\"\n },\n \"keynote1\":{\n \"value\": \"\u5de7\u514b\u529b\",\n \"color\": \"#173177\"\n },\n \"keynote2\": {\n \"value\": \"39.8\u5143\",\n \"color\": \"#173177\"\n },\n \"keynote3\": {\n \"value\": \"2014\u5e749\u670816\u65e5\",\n \"color\": \"#173177\"\n },\n \"remark\":{\n \"value\": \"\u6b22\u8fce\u518d\u6b21\u8d2d\u4e70\uff01\",\n \"color\": \"#173177\"\n }\n }\n :param url: \u8df3\u8f6c\u5730\u5740 (\u9ed8\u8ba4\u4e3a\u7a7a)\n :param topcolor: \u9876\u90e8\u989c\u8272RGB\u503c (\u9ed8\u8ba4 '#FF0000' )\n :return: \u8fd4\u56de\u7684 JSON \u6570\u636e\u5305\n \"\"\"\n unicode_data = {}\n if data:\n unicode_data = self._transcoding_dict(data)\n\n return self.request.post(\n url='https://api.weixin.qq.com/cgi-bin/message/template/send',\n data={\n 'touser': user_id,\n \"template_id\": template_id,\n \"url\": url,\n \"topcolor\": topcolor,\n \"data\": unicode_data\n }\n )"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nchecking if the error code is set and raise an exception if not", "response": "def _check_official_error(self, json_data):\n \"\"\"\n \u68c0\u6d4b\u5fae\u4fe1\u516c\u4f17\u5e73\u53f0\u8fd4\u56de\u503c\u4e2d\u662f\u5426\u5305\u542b\u9519\u8bef\u7684\u8fd4\u56de\u7801\n :raises OfficialAPIError: \u5982\u679c\u8fd4\u56de\u7801\u63d0\u793a\u6709\u9519\u8bef\uff0c\u629b\u51fa\u5f02\u5e38\uff1b\u5426\u5219\u8fd4\u56de True\n \"\"\"\n if \"errcode\" in json_data and json_data[\"errcode\"] != 0:\n raise OfficialAPIError(errcode=json_data.get('errcode'), errmsg=json_data.get('errmsg', ''))"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef xml2dict(self):\n self._remove_whitespace_nodes(self._doc.childNodes[0])\n return self._element2dict(self._doc.childNodes[0])", "response": "\u5c06 XML \u8f6c\u6362\u4e3a dict"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _element2dict(self, parent):\n d = {}\n for node in parent.childNodes:\n if not isinstance(node, minidom.Element):\n continue\n if not node.hasChildNodes():\n continue\n\n if node.childNodes[0].nodeType == minidom.Node.ELEMENT_NODE:\n try:\n d[node.tagName]\n except KeyError:\n d[node.tagName] = []\n d[node.tagName].append(self._element2dict(node))\n elif len(node.childNodes) == 1 and node.childNodes[0].nodeType in [minidom.Node.CDATA_SECTION_NODE, minidom.Node.TEXT_NODE]:\n d[node.tagName] = node.childNodes[0].data\n return d", "response": "Convert XML element to dict."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _remove_whitespace_nodes(self, node, unlink=True):\n remove_list = []\n for child in node.childNodes:\n if child.nodeType == Node.TEXT_NODE and not child.data.strip():\n remove_list.append(child)\n elif child.hasChildNodes():\n self._remove_whitespace_nodes(child, unlink)\n for node in remove_list:\n node.parentNode.removeChild(node)\n if unlink:\n node.unlink()", "response": "Removes whitespace nodes from a node."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nconverts value to binary", "response": "def to_binary(value, encoding='utf-8'):\n \"\"\"\u5c06 values \u8f6c\u4e3a bytes\uff0c\u9ed8\u8ba4\u7f16\u7801 utf-8\n\n :param value: \u5f85\u8f6c\u6362\u7684\u503c\n :param encoding: \u7f16\u7801\n \"\"\"\n if not value:\n return b''\n if isinstance(value, six.binary_type):\n return value\n if isinstance(value, six.text_type):\n return value.encode(encoding)\n\n if six.PY3:\n return six.binary_type(str(value), encoding) # For Python 3\n return six.binary_type(value)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _transcoding(cls, data):\n if not data:\n return data\n\n result = None\n if isinstance(data, str) and hasattr(data, 'decode'):\n result = data.decode('utf-8')\n else:\n result = data\n return result", "response": "Transcoding data to a dict."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _transcoding_list(cls, data):\n if not isinstance(data, list):\n raise ValueError('Parameter data must be list object.')\n\n result = []\n for item in data:\n if isinstance(item, dict):\n result.append(cls._transcoding_dict(item))\n elif isinstance(item, list):\n result.append(cls._transcoding_list(item))\n else:\n result.append(item)\n return result", "response": "Transcoding a list of items into a list of items."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nconverting dict to dict.", "response": "def _transcoding_dict(cls, data):\n \"\"\"\n \u7f16\u7801\u8f6c\u6362 for dict\n :param data: \u9700\u8981\u8f6c\u6362\u7684 dict \u6570\u636e\n :return: \u8f6c\u6362\u597d\u7684 dict\n \"\"\"\n if not isinstance(data, dict):\n raise ValueError('Parameter data must be dict object.')\n\n result = {}\n for k, v in data.items():\n k = cls._transcoding(k)\n if isinstance(v, dict):\n v = cls._transcoding_dict(v)\n elif isinstance(v, list):\n v = cls._transcoding_list(v)\n else:\n v = cls._transcoding(v)\n result.update({k: v})\n return result"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef encode(cls, text):\n text_length = len(text)\n # \u8ba1\u7b97\u9700\u8981\u586b\u5145\u7684\u4f4d\u6570\n amount_to_pad = cls.block_size - (text_length % cls.block_size)\n if amount_to_pad == 0:\n amount_to_pad = cls.block_size\n # \u83b7\u5f97\u8865\u4f4d\u6240\u7528\u7684\u5b57\u7b26\n pad = to_binary(chr(amount_to_pad))\n return text + pad * amount_to_pad", "response": "Encodes the given text into a base64 - encoded version of the object."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef decode(cls, decrypted):\n pad = ord(decrypted[-1])\n if pad < 1 or pad > 32:\n pad = 0\n return decrypted[:-pad]", "response": "Decode a decrypted message into a string."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef decrypt(self, text, appid):\n try:\n cryptor = AES.new(self.key, self.mode, self.key[:16])\n # \u4f7f\u7528BASE64\u5bf9\u5bc6\u6587\u8fdb\u884c\u89e3\u7801\uff0c\u7136\u540eAES-CBC\u89e3\u5bc6\n plain_text = cryptor.decrypt(base64.b64decode(text))\n except Exception as e:\n raise DecryptAESError(e)\n\n try:\n if six.PY2:\n pad = ord(plain_text[-1])\n else:\n pad = plain_text[-1]\n # \u53bb\u6389\u8865\u4f4d\u5b57\u7b26\u4e32\n # pkcs7 = PKCS7Encoder()\n # plain_text = pkcs7.encode(plain_text)\n # \u53bb\u966416\u4f4d\u968f\u673a\u5b57\u7b26\u4e32\n content = plain_text[16:-pad]\n xml_len = socket.ntohl(struct.unpack(\"I\", content[: 4])[0])\n xml_content = content[4: xml_len + 4]\n from_appid = content[xml_len + 4:]\n except Exception as e:\n raise IllegalBuffer(e)\n if from_appid != appid:\n raise ValidateAppIDError()\n return xml_content", "response": "Decrypt a text and return the XML content."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _check_signature(self, msg_signature, timestamp, nonce, echostr):\n signature = get_sha1_signature(self.__token, timestamp, nonce, echostr)\n if not signature == msg_signature:\n raise ValidateSignatureError()\n try:\n return self.__pc.decrypt(echostr, self.__id)\n except DecryptAESError as e:\n raise ValidateSignatureError(e)", "response": "Check if the message signature is correct."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _decrypt_message(self, msg, msg_signature, timestamp, nonce):\n timestamp = to_binary(timestamp)\n nonce = to_binary(nonce)\n if isinstance(msg, six.string_types):\n try:\n msg = xmltodict.parse(to_text(msg))['xml']\n except Exception as e:\n raise ParseError(e)\n\n encrypt = msg['Encrypt']\n signature = get_sha1_signature(self.__token, timestamp, nonce, encrypt)\n if signature != msg_signature:\n raise ValidateSignatureError()\n return self.__pc.decrypt(encrypt, self.__id)", "response": "\u68c0\u9a8c\u6d88\u606f\u7684\u771f\u5b9e\u6027\uff0c\u5e76\u4e14\u83b7\u53d6\u89e3\u5bc6\u540e\u7684\u660e\u6587\n\n :param msg: \u5bc6\u6587\uff0c\u5bf9\u5e94POST\u8bf7\u6c42\u7684\u6570\u636e\n :param msg_signature: \u7b7e\u540d\u4e32\uff0c\u5bf9\u5e94URL\u53c2\u6570\u7684msg_signature\n :param timestamp: \u65f6\u95f4\u6233\uff0c\u5bf9\u5e94URL\u53c2\u6570\u7684timestamp\n :param nonce: \u968f\u673a\u4e32\uff0c\u5bf9\u5e94URL\u53c2\u6570\u7684nonce\n :return: \u89e3\u5bc6\u540e\u7684\u539f\u6587"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Lastovka_Shaw(T, similarity_variable, cyclic_aliphatic=False):\n r'''Calculate ideal-gas constant-pressure heat capacitiy with the similarity\n variable concept and method as shown in [1]_.\n\n .. math::\n C_p^0 = \\left(A_2 + \\frac{A_1 - A_2}{1 + \\exp(\\frac{\\alpha-A_3}{A_4})}\\right)\n + (B_{11} + B_{12}\\alpha)\\left(-\\frac{(C_{11} + C_{12}\\alpha)}{T}\\right)^2\n \\frac{\\exp(-(C_{11} + C_{12}\\alpha)/T)}{[1-\\exp(-(C_{11}+C_{12}\\alpha)/T)]^2}\\\\\n + (B_{21} + B_{22}\\alpha)\\left(-\\frac{(C_{21} + C_{22}\\alpha)}{T}\\right)^2\n \\frac{\\exp(-(C_{21} + C_{22}\\alpha)/T)}{[1-\\exp(-(C_{21}+C_{22}\\alpha)/T)]^2}\n\n Parameters\n ----------\n T : float\n Temperature of gas [K]\n similarity_variable : float\n similarity variable as defined in [1]_, [mol/g]\n\n Returns\n -------\n Cpg : float\n Gas constant-pressure heat capacitiy, [J/kg/K]\n\n Notes\n -----\n Original model is in terms of J/g/K. Note that the model is for predicting\n mass heat capacity, not molar heat capacity like most other methods!\n\n A1 = 0.58, A2 = 1.25, A3 = 0.17338003, A4 = 0.014, B11 = 0.73917383,\n B12 = 8.88308889, C11 = 1188.28051, C12 = 1813.04613, B21 = 0.0483019,\n B22 = 4.35656721, C21 = 2897.01927, C22 = 5987.80407.\n\n Examples\n --------\n >>> Lastovka_Shaw(1000.0, 0.1333)\n 2467.113309084757\n\n References\n ----------\n .. [1] Lastovka, Vaclav, and John M. Shaw. \"Predictive Correlations for\n Ideal Gas Heat Capacities of Pure Hydrocarbons and Petroleum Fractions.\"\n Fluid Phase Equilibria 356 (October 25, 2013): 338-370.\n doi:10.1016/j.fluid.2013.07.023.\n '''\n a = similarity_variable\n if cyclic_aliphatic:\n A1 = -0.1793547\n A2 = 3.86944439\n first = A1 + A2*a\n else:\n A1 = 0.58\n A2 = 1.25\n A3 = 0.17338003 # 803 instead of 8003 in another paper\n A4 = 0.014\n first = A2 + (A1-A2)/(1. + exp((a - A3)/A4))\n # Personal communication confirms the change\n\n B11 = 0.73917383\n B12 = 8.88308889\n C11 = 1188.28051\n C12 = 1813.04613\n B21 = 0.0483019\n B22 = 4.35656721\n C21 = 2897.01927\n C22 = 5987.80407\n Cp = first + (B11 + B12*a)*((C11+C12*a)/T)**2*exp(-(C11 + C12*a)/T)/(1.-exp(-(C11+C12*a)/T))**2\n Cp += (B21 + B22*a)*((C21+C22*a)/T)**2*exp(-(C21 + C22*a)/T)/(1.-exp(-(C21+C22*a)/T))**2\n return Cp*1000.", "response": "Calculate ideal - gas constant - pressure heat capacitiy with the similarity variable concept and method as shown in [ 1 ] _."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Lastovka_Shaw_integral_over_T(T, similarity_variable, cyclic_aliphatic=False):\n r'''Calculate the integral over temperature of ideal-gas constant-pressure \n heat capacitiy with the similarity variable concept and method as shown in\n [1]_.\n\n Parameters\n ----------\n T : float\n Temperature of gas [K]\n similarity_variable : float\n similarity variable as defined in [1]_, [mol/g]\n\n Returns\n -------\n S : float\n Difference in entropy from 0 K, [J/kg/K]\n\n Notes\n -----\n Original model is in terms of J/g/K. Note that the model is for predicting\n mass heat capacity, not molar heat capacity like most other methods!\n Integral was computed with SymPy.\n\n See Also\n --------\n Lastovka_Shaw\n Lastovka_Shaw_integral\n\n Examples\n --------\n >>> Lastovka_Shaw_integral_over_T(300.0, 0.1333)\n 3609.791928945323\n\n References\n ----------\n .. [1] Lastovka, Vaclav, and John M. Shaw. \"Predictive Correlations for\n Ideal Gas Heat Capacities of Pure Hydrocarbons and Petroleum Fractions.\"\n Fluid Phase Equilibria 356 (October 25, 2013): 338-370.\n doi:10.1016/j.fluid.2013.07.023.\n '''\n from cmath import log, exp\n a = similarity_variable\n if cyclic_aliphatic:\n A1 = -0.1793547\n A2 = 3.86944439\n first = A1 + A2*a\n else:\n A1 = 0.58\n A2 = 1.25\n A3 = 0.17338003 # 803 instead of 8003 in another paper\n A4 = 0.014\n first = A2 + (A1-A2)/(1. + exp((a - A3)/A4))\n\n a2 = a*a\n B11 = 0.73917383\n B12 = 8.88308889\n C11 = 1188.28051\n C12 = 1813.04613\n B21 = 0.0483019\n B22 = 4.35656721\n C21 = 2897.01927\n C22 = 5987.80407\n S = (first*log(T) + (-B11 - B12*a)*log(exp((-C11 - C12*a)/T) - 1.) \n + (-B11*C11 - B11*C12*a - B12*C11*a - B12*C12*a2)/(T*exp((-C11\n - C12*a)/T) - T) - (B11*C11 + B11*C12*a + B12*C11*a + B12*C12*a2)/T)\n S += ((-B21 - B22*a)*log(exp((-C21 - C22*a)/T) - 1.) + (-B21*C21 - B21*C22*a\n - B22*C21*a - B22*C22*a2)/(T*exp((-C21 - C22*a)/T) - T) - (B21*C21\n + B21*C22*a + B22*C21*a + B22*C22*a**2)/T)\n # There is a non-real component, but it is only a function of similariy \n # variable and so will always cancel out.\n return S.real*1000.", "response": "r Calculates the integral over temperature of ideal - gas constant - pressure vector with the similarity variable concept and method as shown in SymPy."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef TRCCp_integral(T, a0, a1, a2, a3, a4, a5, a6, a7, I=0):\n r'''Integrates ideal gas heat capacity using the model developed in [1]_.\n Best used as a delta only.\n\n The difference in enthalpy with respect to 0 K is given by:\n\n .. math::\n \\frac{H(T) - H^{ref}}{RT} = a_0 + a_1x(a_2)/(a_2T) + I/T + h(T)/T\n \n h(T) = (a_5 + a_7)\\left[(2a_3 + 8a_4)\\ln(1-y)+ \\left\\{a_3\\left(1 + \n \\frac{1}{1-y}\\right) + a_4\\left(7 + \\frac{1}{1-y}\\right)\\right\\}y\n + a_4\\left\\{3y^2 + (5/3)y^3 + y^4 + (3/5)y^5 + (1/3)y^6\\right\\} \n + (1/7)\\left\\{a_4 - \\frac{a_5}{(a_6+a_7)^2}\\right\\}y^7\\right]\n \n h(T) = 0 \\text{ for } T \\le a_7\n\n y = \\frac{T-a_7}{T+a_6} \\text{ for } T > a_7 \\text{ otherwise } 0\n\n Parameters\n ----------\n T : float\n Temperature [K]\n a1-a7 : float\n Coefficients\n I : float, optional\n Integral offset\n\n Returns\n -------\n H-H(0) : float\n Difference in enthalpy from 0 K , [J/mol]\n\n Notes\n -----\n Analytical integral as provided in [1]_ and verified with numerical\n integration. \n\n Examples\n --------\n >>> TRCCp_integral(298.15, 4.0, 7.65E5, 720., 3.565, -0.052, -1.55E6, 52., \n ... 201., 1.2)\n 10802.532600592816\n \n References\n ----------\n .. [1] Kabo, G. J., and G. N. Roganov. Thermodynamics of Organic Compounds\n in the Gas State, Volume II: V. 2. College Station, Tex: CRC Press, 1994.\n '''\n if T <= a7:\n y = 0.\n else:\n y = (T - a7)/(T + a6)\n y2 = y*y\n y4 = y2*y2\n if T <= a7:\n h = 0.0\n else:\n first = a6 + a7\n second = (2.*a3 + 8.*a4)*log(1. - y)\n third = (a3*(1. + 1./(1. - y)) + a4*(7. + 1./(1. - y)))*y\n fourth = a4*(3.*y2 + 5./3.*y*y2 + y4 + 0.6*y4*y + 1/3.*y4*y2)\n fifth = 1/7.*(a4 - a5/((a6 + a7)**2))*y4*y2*y\n h = first*(second + third + fourth + fifth)\n return (a0 + a1*exp(-a2/T)/(a2*T) + I/T + h/T)*R*T", "response": "Integrates ideal gas heat capacity using the model developed in [ 1 ] _."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a base class for a rowlinson - bonded liquid with the CSP method", "response": "def Rowlinson_Bondi(T, Tc, omega, Cpgm):\n r'''Calculate liquid constant-pressure heat capacitiy with the CSP method\n shown in [1]_.\n\n The heat capacity of a liquid is given by:\n\n .. math::\n \\frac{Cp^L - Cp^{ig}}{R} = 1.45 + 0.45(1-T_r)^{-1} + 0.25\\omega\n [17.11 + 25.2(1-T_r)^{1/3}T_r^{-1} + 1.742(1-T_r)^{-1}]\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n omega : float\n Acentric factor for fluid, [-]\n Cpgm : float\n Constant-pressure gas heat capacity, [J/mol/K]\n\n Returns\n -------\n Cplm : float\n Liquid constant-pressure heat capacitiy, [J/mol/K]\n\n Notes\n -----\n Less accurate than `Rowlinson_Poling`.\n\n Examples\n --------\n >>> Rowlinson_Bondi(T=373.28, Tc=535.55, omega=0.323, Cpgm=119.342)\n 175.39760730048116\n\n References\n ----------\n .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n .. [2] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n .. [3] J.S. Rowlinson, Liquids and Liquid Mixtures, 2nd Ed.,\n Butterworth, London (1969).\n '''\n Tr = T/Tc\n Cplm = Cpgm + R*(1.45 + 0.45/(1.-Tr) + 0.25*omega*(17.11\n + 25.2*(1-Tr)**(1/3.)/Tr + 1.742/(1.-Tr)))\n return Cplm"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Dadgostar_Shaw(T, similarity_variable):\n r'''Calculate liquid constant-pressure heat capacitiy with the similarity\n variable concept and method as shown in [1]_.\n\n .. math::\n C_{p} = 24.5(a_{11}\\alpha + a_{12}\\alpha^2)+ (a_{21}\\alpha\n + a_{22}\\alpha^2)T +(a_{31}\\alpha + a_{32}\\alpha^2)T^2\n\n Parameters\n ----------\n T : float\n Temperature of liquid [K]\n similarity_variable : float\n similarity variable as defined in [1]_, [mol/g]\n\n Returns\n -------\n Cpl : float\n Liquid constant-pressure heat capacitiy, [J/kg/K]\n\n Notes\n -----\n Many restrictions on its use.\n\n Original model is in terms of J/g/K. Note that the model is for predicting\n mass heat capacity, not molar heat capacity like most other methods!\n\n a11 = -0.3416; a12 = 2.2671; a21 = 0.1064; a22 = -0.3874l;\n a31 = -9.8231E-05; a32 = 4.182E-04\n\n Examples\n --------\n >>> Dadgostar_Shaw(355.6, 0.139)\n 1802.5291501191516\n\n References\n ----------\n .. [1] Dadgostar, Nafiseh, and John M. Shaw. \"A Predictive Correlation for\n the Constant-Pressure Specific Heat Capacity of Pure and Ill-Defined\n Liquid Hydrocarbons.\" Fluid Phase Equilibria 313 (January 15, 2012):\n 211-226. doi:10.1016/j.fluid.2011.09.015.\n '''\n a = similarity_variable\n a11 = -0.3416\n a12 = 2.2671\n a21 = 0.1064\n a22 = -0.3874\n a31 = -9.8231E-05\n a32 = 4.182E-04\n\n # Didn't seem to improve the comparison; sum of errors on some\n # points included went from 65.5 to 286.\n # Author probably used more precision in their calculation.\n# theta = 151.8675\n# constant = 3*R*(theta/T)**2*exp(theta/T)/(exp(theta/T)-1)**2\n constant = 24.5\n\n Cp = (constant*(a11*a + a12*a**2) + (a21*a + a22*a**2)*T\n + (a31*a + a32*a**2)*T**2)\n Cp = Cp*1000 # J/g/K to J/kg/K\n return Cp", "response": "r A Predictive Correlation for a Liquid constant - pressure heat capacitiy with the similarity variable concept and method as shown in [ 1 ] _."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Zabransky_quasi_polynomial(T, Tc, a1, a2, a3, a4, a5, a6):\n r'''Calculates liquid heat capacity using the model developed in [1]_.\n\n .. math::\n \\frac{C}{R}=A_1\\ln(1-T_r) + \\frac{A_2}{1-T_r}\n + \\sum_{j=0}^m A_{j+3} T_r^j\n\n Parameters\n ----------\n T : float\n Temperature [K]\n Tc : float\n Critical temperature of fluid, [K]\n a1-a6 : float\n Coefficients\n\n Returns\n -------\n Cp : float\n Liquid heat capacity, [J/mol/K]\n\n Notes\n -----\n Used only for isobaric heat capacities, not saturation heat capacities.\n Designed for reasonable extrapolation behavior caused by using the reduced\n critical temperature. Used by the authors of [1]_ when critical temperature\n was available for the fluid.\n Analytical integrals are available for this expression.\n\n Examples\n --------\n >>> Zabransky_quasi_polynomial(330, 591.79, -3.12743, 0.0857315, 13.7282, 1.28971, 6.42297, 4.10989)\n 165.4728226923247\n\n References\n ----------\n .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski.\n Heat Capacity of Liquids: Critical Review and Recommended Values.\n 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996.\n '''\n Tr = T/Tc\n return R*(a1*log(1-Tr) + a2/(1-Tr) + a3 + a4*Tr + a5*Tr**2 + a6*Tr**3)", "response": "r Zabransky - quasi - polarized version of the formula."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Zabransky_quasi_polynomial_integral_over_T(T, Tc, a1, a2, a3, a4, a5, a6):\n r'''Calculates the integral of liquid heat capacity over T using the \n quasi-polynomial model developed in [1]_.\n\n Parameters\n ----------\n T : float\n Temperature [K]\n a1-a6 : float\n Coefficients\n\n Returns\n -------\n S : float\n Difference in entropy from 0 K, [J/mol/K]\n\n Notes\n -----\n The analytical integral was derived with Sympy. It requires the \n Polylog(2,x) function, which is unimplemented in SciPy. A very accurate \n numerical approximation was implemented as :obj:`thermo.utils.polylog2`.\n Relatively slow due to the use of that special function.\n\n Examples\n --------\n >>> S2 = Zabransky_quasi_polynomial_integral_over_T(300, 591.79, -3.12743, \n ... 0.0857315, 13.7282, 1.28971, 6.42297, 4.10989)\n >>> S1 = Zabransky_quasi_polynomial_integral_over_T(200, 591.79, -3.12743, \n ... 0.0857315, 13.7282, 1.28971, 6.42297, 4.10989)\n >>> S2 - S1\n 59.16997291893654\n \n References\n ----------\n .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski.\n Heat Capacity of Liquids: Critical Review and Recommended Values.\n 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996.\n '''\n term = T - Tc\n logT = log(T)\n Tc2 = Tc*Tc\n Tc3 = Tc2*Tc\n return R*(a3*logT -a1*polylog2(T/Tc) - a2*(-logT + 0.5*log(term*term))\n + T*(T*(T*a6/(3.*Tc3) + a5/(2.*Tc2)) + a4/Tc))", "response": "r Calculates the integral of liquid heat capacity over T using the Zabransky - quasi - polar model developed in [ 1 ]."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Zabransky_cubic_integral(T, a1, a2, a3, a4):\n r'''Calculates the integral of liquid heat capacity using the model \n developed in [1]_.\n\n Parameters\n ----------\n T : float\n Temperature [K]\n a1-a4 : float\n Coefficients\n\n Returns\n -------\n H : float\n Difference in enthalpy from 0 K, [J/mol]\n\n Notes\n -----\n The analytical integral was derived with Sympy; it is a simple polynomial.\n\n Examples\n --------\n >>> Zabransky_cubic_integral(298.15, 20.9634, -10.1344, 2.8253, -0.256738)\n 31051.679845520586\n\n References\n ----------\n .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski.\n Heat Capacity of Liquids: Critical Review and Recommended Values.\n 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996.\n '''\n T = T/100.\n return 100*R*T*(T*(T*(T*a4*0.25 + a3/3.) + a2*0.5) + a1)", "response": "r Calculates the integral of liquid heat capacity using the model \n developed in [ 1 ]."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Zabransky_cubic_integral_over_T(T, a1, a2, a3, a4):\n r'''Calculates the integral of liquid heat capacity over T using the model \n developed in [1]_.\n\n Parameters\n ----------\n T : float\n Temperature [K]\n a1-a4 : float\n Coefficients\n\n Returns\n -------\n S : float\n Difference in entropy from 0 K, [J/mol/K]\n\n Notes\n -----\n The analytical integral was derived with Sympy; it is a simple polynomial,\n plus a logarithm\n\n Examples\n --------\n >>> Zabransky_cubic_integral_over_T(298.15, 20.9634, -10.1344, 2.8253, \n ... -0.256738)\n 24.73245695987246\n\n References\n ----------\n .. [1] Zabransky, M., V. Ruzicka Jr, V. Majer, and Eugene S. Domalski.\n Heat Capacity of Liquids: Critical Review and Recommended Values.\n 2 Volume Set. Washington, D.C.: Amer Inst of Physics, 1996.\n '''\n T = T/100.\n return R*(T*(T*(T*a4/3 + a3/2) + a2) + a1*log(T))", "response": "r Calculates the integral of liquid heat capacity over T using the Zabransky model."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Lastovka_solid_integral(T, similarity_variable):\n r'''Integrates solid constant-pressure heat capacitiy with the similarity\n variable concept and method as shown in [1]_.\n \n Uses a explicit form as derived with Sympy.\n\n Parameters\n ----------\n T : float\n Temperature of solid [K]\n similarity_variable : float\n similarity variable as defined in [1]_, [mol/g]\n\n Returns\n -------\n H : float\n Difference in enthalpy from 0 K, [J/kg]\n\n Notes\n -----\n Original model is in terms of J/g/K. Note that the model is for predicting\n mass heat capacity, not molar heat capacity like most other methods!\n\n See Also\n --------\n Lastovka_solid\n\n Examples\n --------\n >>> Lastovka_solid_integral(300, 0.2139)\n 283246.1242170376\n\n References\n ----------\n .. [1] La\u0161tovka, V\u00e1clav, Michal Fulem, Mildred Becerra, and John M. Shaw.\n \"A Similarity Variable for Estimating the Heat Capacity of Solid Organic\n Compounds: Part II. Application: Heat Capacity Calculation for\n Ill-Defined Organic Solids.\" Fluid Phase Equilibria 268, no. 1-2\n (June 25, 2008): 134-41. doi:10.1016/j.fluid.2008.03.018.\n '''\n A1 = 0.013183\n A2 = 0.249381\n theta = 151.8675\n C1 = 0.026526\n C2 = -0.024942\n D1 = 0.000025\n D2 = -0.000123\n similarity_variable2 = similarity_variable*similarity_variable\n \n return (T*T*T*(1000.*D1*similarity_variable/3. \n + 1000.*D2*similarity_variable2/3.) + T*T*(500.*C1*similarity_variable \n + 500.*C2*similarity_variable2)\n + (3000.*A1*R*similarity_variable*theta\n + 3000.*A2*R*similarity_variable2*theta)/(exp(theta/T) - 1.))", "response": "Integrates solid constant - pressure heat capacitiy with the similarity variable as derived with Sympy."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Lastovka_solid_integral_over_T(T, similarity_variable):\n r'''Integrates over T solid constant-pressure heat capacitiy with the \n similarity variable concept and method as shown in [1]_.\n \n Uses a explicit form as derived with Sympy.\n\n Parameters\n ----------\n T : float\n Temperature of solid [K]\n similarity_variable : float\n similarity variable as defined in [1]_, [mol/g]\n\n Returns\n -------\n S : float\n Difference in entropy from 0 K, [J/kg/K]\n\n Notes\n -----\n Original model is in terms of J/g/K. Note that the model is for predicting\n mass heat capacity, not molar heat capacity like most other methods!\n\n See Also\n --------\n Lastovka_solid\n\n Examples\n --------\n >>> Lastovka_solid_integral_over_T(300, 0.2139)\n 1947.553552666818\n\n References\n ----------\n .. [1] La\u0161tovka, V\u00e1clav, Michal Fulem, Mildred Becerra, and John M. Shaw.\n \"A Similarity Variable for Estimating the Heat Capacity of Solid Organic\n Compounds: Part II. Application: Heat Capacity Calculation for\n Ill-Defined Organic Solids.\" Fluid Phase Equilibria 268, no. 1-2\n (June 25, 2008): 134-41. doi:10.1016/j.fluid.2008.03.018.\n '''\n A1 = 0.013183\n A2 = 0.249381\n theta = 151.8675\n C1 = 0.026526\n C2 = -0.024942\n D1 = 0.000025\n D2 = -0.000123\n \n sim2 = similarity_variable*similarity_variable\n exp_theta_T = exp(theta/T)\n \n return (-3000.*R*similarity_variable*(A1 + A2*similarity_variable)*log(exp_theta_T - 1.) \n + T**2*(500.*D1*similarity_variable + 500.*D2*sim2)\n + T*(1000.*C1*similarity_variable + 1000.*C2*sim2)\n + (3000.*A1*R*similarity_variable*theta \n + 3000.*A2*R*sim2*theta)/(T*exp_theta_T - T) \n + (3000.*A1*R*similarity_variable*theta \n + 3000.*A2*R*sim2*theta)/T)", "response": "Integrates over T solid constant - pressure heat capacitiy with the given similarity variable."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef calculate(self, T, method):\n r'''Method to calculate surface tension of a liquid at temperature `T`\n with a given method.\n\n This method has no exception handling; see `T_dependent_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate heat capacity, [K]\n method : str\n Method name to use\n\n Returns\n -------\n Cp : float\n Calculated heat capacity, [J/mol/K]\n '''\n if method == TRCIG:\n Cp = TRCCp(T, *self.TRCIG_coefs)\n elif method == COOLPROP:\n Cp = PropsSI('Cp0molar', 'T', T,'P', 101325.0, self.CASRN)\n elif method == POLING:\n Cp = R*(self.POLING_coefs[0] + self.POLING_coefs[1]*T\n + self.POLING_coefs[2]*T**2 + self.POLING_coefs[3]*T**3\n + self.POLING_coefs[4]*T**4)\n elif method == POLING_CONST:\n Cp = self.POLING_constant\n elif method == CRCSTD:\n Cp = self.CRCSTD_constant\n elif method == LASTOVKA_SHAW:\n Cp = Lastovka_Shaw(T, self.similarity_variable)\n Cp = property_mass_to_molar(Cp, self.MW)\n elif method in self.tabular_data:\n Cp = self.interpolate(T, method)\n return Cp", "response": "r Method to calculate surface tension of a liquid at temperature T with a given method."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef calculate_integral_over_T(self, T1, T2, method):\n r'''Method to calculate the integral of a property over temperature\n with respect to temperature, using a specified method. Implements the \n analytical integrals of all available methods except for tabular data.\n \n Parameters\n ----------\n T1 : float\n Lower limit of integration, [K]\n T2 : float\n Upper limit of integration, [K]\n method : str\n Method for which to find the integral\n\n Returns\n -------\n integral : float\n Calculated integral of the property over the given range, \n [`units`]\n '''\n if method == TRCIG:\n S2 = TRCCp_integral_over_T(T2, *self.TRCIG_coefs)\n S1 = TRCCp_integral_over_T(T1, *self.TRCIG_coefs)\n return S2 - S1\n elif method == CRCSTD:\n return self.CRCSTD_constant*log(T2/T1)\n elif method == POLING_CONST:\n return self.POLING_constant*log(T2/T1)\n elif method == POLING:\n A, B, C, D, E = self.POLING_coefs\n S2 = ((((0.25*E)*T2 + D/3.)*T2 + 0.5*C)*T2 + B)*T2 \n S1 = ((((0.25*E)*T1 + D/3.)*T1 + 0.5*C)*T1 + B)*T1\n return R*(S2-S1 + A*log(T2/T1))\n elif method == LASTOVKA_SHAW:\n dS = (Lastovka_Shaw_integral_over_T(T2, self.similarity_variable)\n - Lastovka_Shaw_integral_over_T(T1, self.similarity_variable))\n return property_mass_to_molar(dS, self.MW)\n elif method in self.tabular_data or method == COOLPROP:\n return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0])\n else:\n raise Exception('Method not valid')", "response": "r Calculates the integral of a property over a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef calculate_integral(self, T1, T2):\n r'''Method to compute the enthalpy integral of heat capacity from \n `T1` to `T2`.\n \n Parameters\n ----------\n T1 : float\n Initial temperature, [K]\n T2 : float\n Final temperature, [K]\n \n Returns\n -------\n dH : float\n Enthalpy difference between `T1` and `T2`, [J/mol]\n ''' \n return (Zabransky_quasi_polynomial_integral(T2, self.Tc, *self.coeffs)\n - Zabransky_quasi_polynomial_integral(T1, self.Tc, *self.coeffs))", "response": "r Method to compute the enthalpy integral of heat capacity from \n T1 to T2."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncalls internally during the parsing of the Zabransky database add coefficients as they are read one per line", "response": "def add_coeffs(self, Tmin, Tmax, coeffs):\n '''Called internally during the parsing of the Zabransky database, to\n add coefficients as they are read one per line'''\n self.n += 1\n if not self.Ts:\n self.Ts = [Tmin, Tmax]\n self.coeff_sets = [coeffs]\n else:\n for ind, T in enumerate(self.Ts):\n if Tmin < T:\n # Under an existing coefficient set - assume Tmax will come from another set\n self.Ts.insert(ind, Tmin) \n self.coeff_sets.insert(ind, coeffs)\n return\n # Must be appended to end instead\n self.Ts.append(Tmax)\n self.coeff_sets.append(coeffs)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndetermining the index at which the coefficients for the current temperature are stored in thecoeff_sets.", "response": "def _coeff_ind_from_T(self, T):\n '''Determines the index at which the coefficients for the current\n temperature are stored in `coeff_sets`.\n '''\n # DO NOT CHANGE\n if self.n == 1:\n return 0\n for i in range(self.n):\n if T <= self.Ts[i+1]:\n return i\n return self.n - 1"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef calculate_integral_over_T(self, T1, T2):\n r'''Method to compute the entropy integral of heat capacity from \n `T1` to `T2`. Analytically integrates across the piecewise spline\n as necessary.\n \n Parameters\n ----------\n T1 : float\n Initial temperature, [K]\n T2 : float\n Final temperature, [K]\n \n Returns\n -------\n dS : float\n Entropy difference between `T1` and `T2`, [J/mol/K]\n ''' \n # Simplify the problem so we can assume T2 >= T1\n if T2 < T1:\n flipped = True\n T1, T2 = T2, T1\n else:\n flipped = False\n \n # Fastest case - only one coefficient set, occurs surprisingly often\n if self.n == 1:\n dS = (Zabransky_cubic_integral_over_T(T2, *self.coeff_sets[0])\n - Zabransky_cubic_integral_over_T(T1, *self.coeff_sets[0]))\n else:\n ind_T1, ind_T2 = self._coeff_ind_from_T(T1), self._coeff_ind_from_T(T2)\n # Second fastest case - both are in the same coefficient set\n if ind_T1 == ind_T2:\n dS = (Zabransky_cubic_integral_over_T(T2, *self.coeff_sets[ind_T2])\n - Zabransky_cubic_integral_over_T(T1, *self.coeff_sets[ind_T1]))\n # Fo through the loop if we need to - inevitably slow \n else:\n dS = (Zabransky_cubic_integral_over_T(self.Ts[ind_T1], *self.coeff_sets[ind_T1])\n - Zabransky_cubic_integral_over_T(T1, *self.coeff_sets[ind_T1]))\n for i in range(ind_T1, ind_T2):\n diff =(Zabransky_cubic_integral_over_T(self.Ts[i+1], *self.coeff_sets[i])\n - Zabransky_cubic_integral_over_T(self.Ts[i], *self.coeff_sets[i]))\n dS += diff\n end = (Zabransky_cubic_integral_over_T(T2, *self.coeff_sets[ind_T2])\n - Zabransky_cubic_integral_over_T(self.Ts[ind_T2], *self.coeff_sets[ind_T2]))\n dS += end\n return -dS if flipped else dS", "response": "r Method to compute the entropy integral of heat capacity from a piecewise spline system from a set of temperature T1 to T2. Analytically integrates across the piecewise spline system and returns the result."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef calculate_integral(self, T1, T2, method):\n r'''Method to calculate the integral of a property with respect to\n temperature, using a specified method. Implements the \n analytical integrals of all available methods except for tabular data,\n the case of multiple coefficient sets needed to encompass the temperature\n range of any of the ZABRANSKY methods, and the CSP methods using the\n vapor phase properties.\n\n Parameters\n ----------\n T1 : float\n Lower limit of integration, [K]\n T2 : float\n Upper limit of integration, [K]\n method : str\n Method for which to find the integral\n\n Returns\n -------\n integral : float\n Calculated integral of the property over the given range, \n [`units*K`]\n '''\n if method == ZABRANSKY_SPLINE:\n return self.Zabransky_spline.calculate_integral(T1, T2)\n elif method == ZABRANSKY_SPLINE_C:\n return self.Zabransky_spline_iso.calculate_integral(T1, T2)\n elif method == ZABRANSKY_SPLINE_SAT:\n return self.Zabransky_spline_sat.calculate_integral(T1, T2)\n elif method == ZABRANSKY_QUASIPOLYNOMIAL:\n return self.Zabransky_quasipolynomial.calculate_integral(T1, T2)\n elif method == ZABRANSKY_QUASIPOLYNOMIAL_C:\n return self.Zabransky_quasipolynomial_iso.calculate_integral(T1, T2)\n elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT:\n return self.Zabransky_quasipolynomial_sat.calculate_integral(T1, T2)\n elif method == POLING_CONST:\n return (T2 - T1)*self.POLING_constant\n elif method == CRCSTD:\n return (T2 - T1)*self.CRCSTD_constant\n elif method == DADGOSTAR_SHAW:\n dH = (Dadgostar_Shaw_integral(T2, self.similarity_variable)\n - Dadgostar_Shaw_integral(T1, self.similarity_variable))\n return property_mass_to_molar(dH, self.MW)\n elif method in self.tabular_data or method == COOLPROP or method in [ROWLINSON_POLING, ROWLINSON_BONDI]:\n return float(quad(self.calculate, T1, T2, args=(method))[0])\n else:\n raise Exception('Method not valid')", "response": "r Calculates the integral of a property with respect to a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef calculate_integral_over_T(self, T1, T2, method):\n r'''Method to calculate the integral of a property over temperature\n with respect to temperature, using a specified method. Implements the \n analytical integrals of all available methods except for tabular data,\n the case of multiple coefficient sets needed to encompass the temperature\n range of any of the ZABRANSKY methods, and the CSP methods using the\n vapor phase properties.\n\n Parameters\n ----------\n T1 : float\n Lower limit of integration, [K]\n T2 : float\n Upper limit of integration, [K]\n method : str\n Method for which to find the integral\n\n Returns\n -------\n integral : float\n Calculated integral of the property over the given range, \n [`units`]\n '''\n if method == ZABRANSKY_SPLINE:\n return self.Zabransky_spline.calculate_integral_over_T(T1, T2)\n elif method == ZABRANSKY_SPLINE_C:\n return self.Zabransky_spline_iso.calculate_integral_over_T(T1, T2)\n elif method == ZABRANSKY_SPLINE_SAT:\n return self.Zabransky_spline_sat.calculate_integral_over_T(T1, T2)\n elif method == ZABRANSKY_QUASIPOLYNOMIAL:\n return self.Zabransky_quasipolynomial.calculate_integral_over_T(T1, T2)\n elif method == ZABRANSKY_QUASIPOLYNOMIAL_C:\n return self.Zabransky_quasipolynomial_iso.calculate_integral_over_T(T1, T2)\n elif method == ZABRANSKY_QUASIPOLYNOMIAL_SAT:\n return self.Zabransky_quasipolynomial_sat.calculate_integral_over_T(T1, T2)\n elif method == POLING_CONST:\n return self.POLING_constant*log(T2/T1)\n elif method == CRCSTD:\n return self.CRCSTD_constant*log(T2/T1)\n elif method == DADGOSTAR_SHAW:\n dS = (Dadgostar_Shaw_integral_over_T(T2, self.similarity_variable)\n - Dadgostar_Shaw_integral_over_T(T1, self.similarity_variable))\n return property_mass_to_molar(dS, self.MW)\n elif method in self.tabular_data or method == COOLPROP or method in [ROWLINSON_POLING, ROWLINSON_BONDI]:\n return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0])\n else:\n raise Exception('Method not valid')", "response": "r Calculates the integral of a property over a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef load_all_methods(self):\n r'''Method which picks out coefficients for the specified chemical\n from the various dictionaries and DataFrames storing it. All data is\n stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,\n and :obj:`all_methods` as a set of methods for which the data exists for.\n\n Called on initialization only. See the source code for the variables at\n which the coefficients are stored. The coefficients can safely be\n altered once the class is initialized. This method can be called again\n to reset the parameters.\n '''\n methods = []\n Tmins, Tmaxs = [], []\n if self.CASRN and self.CASRN in _PerryI and 'c' in _PerryI[self.CASRN]:\n self.PERRY151_Tmin = _PerryI[self.CASRN]['c']['Tmin'] if _PerryI[self.CASRN]['c']['Tmin'] else 0\n self.PERRY151_Tmax = _PerryI[self.CASRN]['c']['Tmax'] if _PerryI[self.CASRN]['c']['Tmax'] else 2000\n self.PERRY151_const = _PerryI[self.CASRN]['c']['Const']\n self.PERRY151_lin = _PerryI[self.CASRN]['c']['Lin']\n self.PERRY151_quad = _PerryI[self.CASRN]['c']['Quad']\n self.PERRY151_quadinv = _PerryI[self.CASRN]['c']['Quadinv']\n methods.append(PERRY151)\n Tmins.append(self.PERRY151_Tmin); Tmaxs.append(self.PERRY151_Tmax)\n if self.CASRN in CRC_standard_data.index and not np.isnan(CRC_standard_data.at[self.CASRN, 'Cpc']):\n self.CRCSTD_Cp = float(CRC_standard_data.at[self.CASRN, 'Cpc'])\n methods.append(CRCSTD)\n if self.MW and self.similarity_variable:\n methods.append(LASTOVKA_S)\n Tmins.append(1.0); Tmaxs.append(10000)\n # Works above roughly 1 K up to 10K.\n self.all_methods = set(methods)\n if Tmins and Tmaxs:\n self.Tmin, self.Tmax = min(Tmins), max(Tmaxs)", "response": "r This method loads all methods for the specified chemicalical hierarchy from the various dictionaries and DataFrames storing them as attributes."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef calculate_integral(self, T1, T2, method):\n r'''Method to calculate the integral of a property with respect to\n temperature, using a specified method. Implements the analytical\n integrals of all available methods except for tabular data.\n \n Parameters\n ----------\n T1 : float\n Lower limit of integration, [K]\n T2 : float\n Upper limit of integration, [K]\n method : str\n Method for which to find the integral\n\n Returns\n -------\n integral : float\n Calculated integral of the property over the given range, \n [`units*K`]\n '''\n if method == PERRY151:\n H2 = (self.PERRY151_const*T2 + 0.5*self.PERRY151_lin*T2**2 \n - self.PERRY151_quadinv/T2 + self.PERRY151_quad*T2**3/3.)\n H1 = (self.PERRY151_const*T1 + 0.5*self.PERRY151_lin*T1**2 \n - self.PERRY151_quadinv/T1 + self.PERRY151_quad*T1**3/3.)\n return (H2-H1)*calorie\n elif method == CRCSTD:\n return (T2-T1)*self.CRCSTD_Cp\n elif method == LASTOVKA_S:\n dH = (Lastovka_solid_integral(T2, self.similarity_variable)\n - Lastovka_solid_integral(T1, self.similarity_variable))\n return property_mass_to_molar(dH, self.MW)\n elif method in self.tabular_data:\n return float(quad(self.calculate, T1, T2, args=(method))[0])\n else:\n raise Exception('Method not valid')", "response": "r Method to calculate the integral of a property with respect to\n temperature T1 T2 using a specified method."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef calculate_integral_over_T(self, T1, T2, method):\n r'''Method to calculate the integral of a property over temperature\n with respect to temperature, using a specified method. Implements the \n analytical integrals of all available methods except for tabular data.\n \n Parameters\n ----------\n T1 : float\n Lower limit of integration, [K]\n T2 : float\n Upper limit of integration, [K]\n method : str\n Method for which to find the integral\n\n Returns\n -------\n integral : float\n Calculated integral of the property over the given range, \n [`units`]\n '''\n if method == PERRY151:\n S2 = (self.PERRY151_const*log(T2) + self.PERRY151_lin*T2 \n - self.PERRY151_quadinv/(2.*T2**2) + 0.5*self.PERRY151_quad*T2**2)\n S1 = (self.PERRY151_const*log(T1) + self.PERRY151_lin*T1\n - self.PERRY151_quadinv/(2.*T1**2) + 0.5*self.PERRY151_quad*T1**2)\n return (S2 - S1)*calorie\n elif method == CRCSTD:\n S2 = self.CRCSTD_Cp*log(T2)\n S1 = self.CRCSTD_Cp*log(T1)\n return (S2 - S1)\n elif method == LASTOVKA_S:\n dS = (Lastovka_solid_integral_over_T(T2, self.similarity_variable)\n - Lastovka_solid_integral_over_T(T1, self.similarity_variable))\n return property_mass_to_molar(dS, self.MW)\n elif method in self.tabular_data:\n return float(quad(lambda T: self.calculate(T, method)/T, T1, T2)[0])\n else:\n raise Exception('Method not valid')", "response": "r Calculates the integral of a property over a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef calculate(self, T, P, zs, ws, method):\n r'''Method to calculate heat capacity of a gas mixture at \n temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n `ws` with a given method.\n\n This method has no exception handling; see `mixture_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the property, [K]\n P : float\n Pressure at which to calculate the property, [Pa]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n method : str\n Name of the method to use\n\n Returns\n -------\n Cpgm : float\n Molar heat capacity of the gas mixture at the given conditions,\n [J/mol]\n '''\n if method == SIMPLE:\n Cpgms = [i(T) for i in self.HeatCapacityGases]\n return mixing_simple(zs, Cpgms)\n else:\n raise Exception('Method not valid')", "response": "r Method to calculate the heat capacity of a gas mixture at \n temperature pressure mole fractions and weight fractions of all species in the mixture at a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Rachford_Rice_flash_error(V_over_F, zs, Ks):\n r'''Calculates the objective function of the Rachford-Rice flash equation.\n This function should be called by a solver seeking a solution to a flash\n calculation. The unknown variable is `V_over_F`, for which a solution\n must be between 0 and 1.\n\n .. math::\n \\sum_i \\frac{z_i(K_i-1)}{1 + \\frac{V}{F}(K_i-1)} = 0\n\n Parameters\n ----------\n V_over_F : float\n Vapor fraction guess [-]\n zs : list[float]\n Overall mole fractions of all species, [-]\n Ks : list[float]\n Equilibrium K-values, [-]\n\n Returns\n -------\n error : float\n Deviation between the objective function at the correct V_over_F\n and the attempted V_over_F, [-]\n\n Notes\n -----\n The derivation is as follows:\n\n .. math::\n F z_i = L x_i + V y_i\n\n x_i = \\frac{z_i}{1 + \\frac{V}{F}(K_i-1)}\n\n \\sum_i y_i = \\sum_i K_i x_i = 1\n\n \\sum_i(y_i - x_i)=0\n\n \\sum_i \\frac{z_i(K_i-1)}{1 + \\frac{V}{F}(K_i-1)} = 0\n\n Examples\n --------\n >>> Rachford_Rice_flash_error(0.5, zs=[0.5, 0.3, 0.2],\n ... Ks=[1.685, 0.742, 0.532])\n 0.04406445591174976\n\n References\n ----------\n .. [1] Rachford, H. H. Jr, and J. D. Rice. \"Procedure for Use of Electronic\n Digital Computers in Calculating Flash Vaporization Hydrocarbon\n Equilibrium.\" Journal of Petroleum Technology 4, no. 10 (October 1,\n 1952): 19-3. doi:10.2118/952327-G.\n '''\n return sum([zi*(Ki-1.)/(1.+V_over_F*(Ki-1.)) for Ki, zi in zip(Ks, zs)])", "response": "r Calculates the objective function of the Rachford - Rice flash equation."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef flash_inner_loop(zs, Ks, AvailableMethods=False, Method=None):\n r'''This function handles the solution of the inner loop of a flash\n calculation, solving for liquid and gas mole fractions and vapor fraction\n based on specified overall mole fractions and K values. As K values are\n weak functions of composition, this should be called repeatedly by an outer\n loop. Will automatically select an algorithm to use if no Method is\n provided. Should always provide a solution.\n\n The automatic algorithm selection will try an analytical solution, and use\n the Rachford-Rice method if there are 4 or more components in the mixture.\n\n Parameters\n ----------\n zs : list[float]\n Overall mole fractions of all species, [-]\n Ks : list[float]\n Equilibrium K-values, [-]\n\n Returns\n -------\n V_over_F : float\n Vapor fraction solution [-]\n xs : list[float]\n Mole fractions of each species in the liquid phase, [-]\n ys : list[float]\n Mole fractions of each species in the vapor phase, [-]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain a solution with the given\n inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n The method name to use. Accepted methods are 'Analytical',\n 'Rachford-Rice', and 'Li-Johns-Ahmadi'. All valid values are also held\n in the list `flash_inner_loop_methods`.\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n a solution for the desired chemical, and will return methods instead of\n `V_over_F`, `xs`, and `ys`.\n\n Notes\n -----\n A total of three methods are available for this function. They are:\n\n * 'Analytical', an exact solution derived with SymPy, applicable only\n only to mixtures of two or three components\n * 'Rachford-Rice', which numerically solves an objective function\n described in :obj:`Rachford_Rice_solution`.\n * 'Li-Johns-Ahmadi', which numerically solves an objective function\n described in :obj:`Li_Johns_Ahmadi_solution`.\n\n Examples\n --------\n >>> flash_inner_loop(zs=[0.5, 0.3, 0.2], Ks=[1.685, 0.742, 0.532])\n (0.6907302627738537, [0.3394086969663437, 0.36505605903717053, 0.29553524399648573], [0.5719036543882892, 0.2708715958055805, 0.1572247498061304])\n '''\n l = len(zs)\n def list_methods():\n methods = []\n if l in [2,3]:\n methods.append('Analytical')\n if l >= 2:\n methods.append('Rachford-Rice')\n if l >= 3:\n methods.append('Li-Johns-Ahmadi')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = 'Analytical' if l < 4 else 'Rachford-Rice'\n if Method == 'Analytical':\n if l == 2:\n z1, z2 = zs\n K1, K2 = Ks\n V_over_F = (-K1*z1 - K2*z2 + z1 + z2)/(K1*K2*z1 + K1*K2*z2 - K1*z1 - K1*z2 - K2*z1 - K2*z2 + z1 + z2)\n elif l == 3:\n z1, z2, z3 = zs\n K1, K2, K3 = Ks\n V_over_F = (-K1*K2*z1/2 - K1*K2*z2/2 - K1*K3*z1/2 - K1*K3*z3/2 + K1*z1 + K1*z2/2 + K1*z3/2 - K2*K3*z2/2 - K2*K3*z3/2 + K2*z1/2 + K2*z2 + K2*z3/2 + K3*z1/2 + K3*z2/2 + K3*z3 - z1 - z2 - z3 - (K1**2*K2**2*z1**2 + 2*K1**2*K2**2*z1*z2 + K1**2*K2**2*z2**2 - 2*K1**2*K2*K3*z1**2 - 2*K1**2*K2*K3*z1*z2 - 2*K1**2*K2*K3*z1*z3 + 2*K1**2*K2*K3*z2*z3 - 2*K1**2*K2*z1*z2 + 2*K1**2*K2*z1*z3 - 2*K1**2*K2*z2**2 - 2*K1**2*K2*z2*z3 + K1**2*K3**2*z1**2 + 2*K1**2*K3**2*z1*z3 + K1**2*K3**2*z3**2 + 2*K1**2*K3*z1*z2 - 2*K1**2*K3*z1*z3 - 2*K1**2*K3*z2*z3 - 2*K1**2*K3*z3**2 + K1**2*z2**2 + 2*K1**2*z2*z3 + K1**2*z3**2 - 2*K1*K2**2*K3*z1*z2 + 2*K1*K2**2*K3*z1*z3 - 2*K1*K2**2*K3*z2**2 - 2*K1*K2**2*K3*z2*z3 - 2*K1*K2**2*z1**2 - 2*K1*K2**2*z1*z2 - 2*K1*K2**2*z1*z3 + 2*K1*K2**2*z2*z3 + 2*K1*K2*K3**2*z1*z2 - 2*K1*K2*K3**2*z1*z3 - 2*K1*K2*K3**2*z2*z3 - 2*K1*K2*K3**2*z3**2 + 4*K1*K2*K3*z1**2 + 4*K1*K2*K3*z1*z2 + 4*K1*K2*K3*z1*z3 + 4*K1*K2*K3*z2**2 + 4*K1*K2*K3*z2*z3 + 4*K1*K2*K3*z3**2 + 2*K1*K2*z1*z2 - 2*K1*K2*z1*z3 - 2*K1*K2*z2*z3 - 2*K1*K2*z3**2 - 2*K1*K3**2*z1**2 - 2*K1*K3**2*z1*z2 - 2*K1*K3**2*z1*z3 + 2*K1*K3**2*z2*z3 - 2*K1*K3*z1*z2 + 2*K1*K3*z1*z3 - 2*K1*K3*z2**2 - 2*K1*K3*z2*z3 + K2**2*K3**2*z2**2 + 2*K2**2*K3**2*z2*z3 + K2**2*K3**2*z3**2 + 2*K2**2*K3*z1*z2 - 2*K2**2*K3*z1*z3 - 2*K2**2*K3*z2*z3 - 2*K2**2*K3*z3**2 + K2**2*z1**2 + 2*K2**2*z1*z3 + K2**2*z3**2 - 2*K2*K3**2*z1*z2 + 2*K2*K3**2*z1*z3 - 2*K2*K3**2*z2**2 - 2*K2*K3**2*z2*z3 - 2*K2*K3*z1**2 - 2*K2*K3*z1*z2 - 2*K2*K3*z1*z3 + 2*K2*K3*z2*z3 + K3**2*z1**2 + 2*K3**2*z1*z2 + K3**2*z2**2)**0.5/2)/(K1*K2*K3*z1 + K1*K2*K3*z2 + K1*K2*K3*z3 - K1*K2*z1 - K1*K2*z2 - K1*K2*z3 - K1*K3*z1 - K1*K3*z2 - K1*K3*z3 + K1*z1 + K1*z2 + K1*z3 - K2*K3*z1 - K2*K3*z2 - K2*K3*z3 + K2*z1 + K2*z2 + K2*z3 + K3*z1 + K3*z2 + K3*z3 - z1 - z2 - z3)\n else:\n raise Exception('Only solutions of one or two variables are available analytically')\n xs = [zi/(1.+V_over_F*(Ki-1.)) for zi, Ki in zip(zs, Ks)]\n ys = [Ki*xi for xi, Ki in zip(xs, Ks)]\n return V_over_F, xs, ys\n elif Method == 'Rachford-Rice':\n return Rachford_Rice_solution(zs=zs, Ks=Ks)\n elif Method == 'Li-Johns-Ahmadi':\n return Li_Johns_Ahmadi_solution(zs=zs, Ks=Ks)\n else:\n raise Exception('Incorrect Method input')", "response": "r This function handles the inner loop of a flash base of a flash base of a mixture of species and K values."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef NRTL(xs, taus, alphas):\n r'''Calculates the activity coefficients of each species in a mixture\n using the Non-Random Two-Liquid (NRTL) method, given their mole fractions,\n dimensionless interaction parameters, and nonrandomness constants. Those\n are normally correlated with temperature in some form, and need to be\n calculated separately.\n\n .. math::\n \\ln(\\gamma_i)=\\frac{\\displaystyle\\sum_{j=1}^{n}{x_{j}\\tau_{ji}G_{ji}}}\n {\\displaystyle\\sum_{k=1}^{n}{x_{k}G_{ki}}}+\\sum_{j=1}^{n}\n {\\frac{x_{j}G_{ij}}{\\displaystyle\\sum_{k=1}^{n}{x_{k}G_{kj}}}}\n {\\left ({\\tau_{ij}-\\frac{\\displaystyle\\sum_{m=1}^{n}{x_{m}\\tau_{mj}\n G_{mj}}}{\\displaystyle\\sum_{k=1}^{n}{x_{k}G_{kj}}}}\\right )}\n\n G_{ij}=\\text{exp}\\left ({-\\alpha_{ij}\\tau_{ij}}\\right )\n\n Parameters\n ----------\n xs : list[float]\n Liquid mole fractions of each species, [-]\n taus : list[list[float]]\n Dimensionless interaction parameters of each compound with each other,\n [-]\n alphas : list[list[float]]\n Nonrandomness constants of each compound interacting with each other, [-]\n\n Returns\n -------\n gammas : list[float]\n Activity coefficient for each species in the liquid mixture, [-]\n\n Notes\n -----\n This model needs N^2 parameters.\n\n One common temperature dependence of the nonrandomness constants is:\n\n .. math::\n \\alpha_{ij}=c_{ij}+d_{ij}T\n\n Most correlations for the interaction parameters include some of the terms\n shown in the following form:\n\n .. math::\n \\tau_{ij}=A_{ij}+\\frac{B_{ij}}{T}+\\frac{C_{ij}}{T^{2}}+D_{ij}\n \\ln{\\left ({T}\\right )}+E_{ij}T^{F_{ij}}\n\n Examples\n --------\n Ethanol-water example, at 343.15 K and 1 MPa:\n\n >>> NRTL(xs=[0.252, 0.748], taus=[[0, -0.178], [1.963, 0]],\n ... alphas=[[0, 0.2974],[.2974, 0]])\n [1.9363183763514304, 1.1537609663170014]\n\n References\n ----------\n .. [1] Renon, Henri, and J. M. Prausnitz. \"Local Compositions in\n Thermodynamic Excess Functions for Liquid Mixtures.\" AIChE Journal 14,\n no. 1 (1968): 135-144. doi:10.1002/aic.690140124.\n .. [2] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:\n Wiley-VCH, 2012.\n '''\n gammas = []\n cmps = range(len(xs))\n Gs = [[exp(-alphas[i][j]*taus[i][j]) for j in cmps] for i in cmps]\n for i in cmps:\n tn1, td1, total2 = 0., 0., 0.\n for j in cmps:\n # Term 1, numerator and denominator\n tn1 += xs[j]*taus[j][i]*Gs[j][i]\n td1 += xs[j]*Gs[j][i]\n # Term 2\n tn2 = xs[j]*Gs[i][j]\n td2 = td3 = sum([xs[k]*Gs[k][j] for k in cmps])\n tn3 = sum([xs[m]*taus[m][j]*Gs[m][j] for m in cmps])\n total2 += tn2/td2*(taus[i][j] - tn3/td3)\n gamma = exp(tn1/td1 + total2)\n gammas.append(gamma)\n return gammas", "response": "r Returns the non - random two - liquid mixture with the same number of non - random parameters."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Wilson(xs, params):\n r'''Calculates the activity coefficients of each species in a mixture\n using the Wilson method, given their mole fractions, and\n dimensionless interaction parameters. Those are normally correlated with\n temperature, and need to be calculated separately.\n\n .. math::\n \\ln \\gamma_i = 1 - \\ln \\left(\\sum_j^N \\Lambda_{ij} x_j\\right)\n -\\sum_j^N \\frac{\\Lambda_{ji}x_j}{\\displaystyle\\sum_k^N \\Lambda_{jk}x_k}\n\n Parameters\n ----------\n xs : list[float]\n Liquid mole fractions of each species, [-]\n params : list[list[float]]\n Dimensionless interaction parameters of each compound with each other,\n [-]\n\n Returns\n -------\n gammas : list[float]\n Activity coefficient for each species in the liquid mixture, [-]\n\n Notes\n -----\n This model needs N^2 parameters.\n\n The original model correlated the interaction parameters using the standard\n pure-component molar volumes of each species at 25\u00b0C, in the following form:\n\n .. math::\n \\Lambda_{ij} = \\frac{V_j}{V_i} \\exp\\left(\\frac{-\\lambda_{i,j}}{RT}\\right)\n\n However, that form has less flexibility and offered no advantage over\n using only regressed parameters.\n\n Most correlations for the interaction parameters include some of the terms\n shown in the following form:\n\n .. math::\n \\ln \\Lambda_{ij} =a_{ij}+\\frac{b_{ij}}{T}+c_{ij}\\ln T + d_{ij}T\n + \\frac{e_{ij}}{T^2} + h_{ij}{T^2}\n\n The Wilson model is not applicable to liquid-liquid systems.\n\n Examples\n --------\n Ethanol-water example, at 343.15 K and 1 MPa:\n\n >>> Wilson([0.252, 0.748], [[1, 0.154], [0.888, 1]])\n [1.8814926087178843, 1.1655774931125487]\n\n References\n ----------\n .. [1] Wilson, Grant M. \"Vapor-Liquid Equilibrium. XI. A New Expression for\n the Excess Free Energy of Mixing.\" Journal of the American Chemical\n Society 86, no. 2 (January 1, 1964): 127-130. doi:10.1021/ja01056a002.\n .. [2] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:\n Wiley-VCH, 2012.\n '''\n gammas = []\n cmps = range(len(xs))\n for i in cmps:\n tot1 = log(sum([params[i][j]*xs[j] for j in cmps]))\n tot2 = 0.\n for j in cmps:\n tot2 += params[j][i]*xs[j]/sum([params[j][k]*xs[k] for k in cmps])\n\n gamma = exp(1. - tot1 - tot2)\n gammas.append(gamma)\n return gammas", "response": "r Returns the activity coefficients of each species in a mixture of liquid - liquid systems."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef UNIQUAC(xs, rs, qs, taus):\n r'''Calculates the activity coefficients of each species in a mixture\n using the Universal quasi-chemical (UNIQUAC) equation, given their mole\n fractions, `rs`, `qs`, and dimensionless interaction parameters. The\n interaction parameters are normally correlated with temperature, and need\n to be calculated separately.\n\n .. math::\n \\ln \\gamma_i = \\ln \\frac{\\Phi_i}{x_i} + \\frac{z}{2} q_i \\ln\n \\frac{\\theta_i}{\\Phi_i}+ l_i - \\frac{\\Phi_i}{x_i}\\sum_j^N x_j l_j\n - q_i \\ln\\left( \\sum_j^N \\theta_j \\tau_{ji}\\right)+ q_i - q_i\\sum_j^N\n \\frac{\\theta_j \\tau_{ij}}{\\sum_k^N \\theta_k \\tau_{kj}}\n\n \\theta_i = \\frac{x_i q_i}{\\displaystyle\\sum_{j=1}^{n} x_j q_j}\n\n \\Phi_i = \\frac{x_i r_i}{\\displaystyle\\sum_{j=1}^{n} x_j r_j}\n\n l_i = \\frac{z}{2}(r_i - q_i) - (r_i - 1)\n\n Parameters\n ----------\n xs : list[float]\n Liquid mole fractions of each species, [-]\n rs : list[float]\n Van der Waals volume parameters for each species, [-]\n qs : list[float]\n Surface area parameters for each species, [-]\n taus : list[list[float]]\n Dimensionless interaction parameters of each compound with each other,\n [-]\n\n Returns\n -------\n gammas : list[float]\n Activity coefficient for each species in the liquid mixture, [-]\n\n Notes\n -----\n This model needs N^2 parameters.\n\n The original expression for the interaction parameters is as follows:\n\n .. math::\n \\tau_{ji} = \\exp\\left(\\frac{-\\Delta u_{ij}}{RT}\\right)\n\n However, it is seldom used. Most correlations for the interaction\n parameters include some of the terms shown in the following form:\n\n .. math::\n \\ln \\tau{ij} =a_{ij}+\\frac{b_{ij}}{T}+c_{ij}\\ln T + d_{ij}T\n + \\frac{e_{ij}}{T^2}\n\n This model is recast in a slightly more computationally efficient way in\n [2]_, as shown below:\n\n .. math::\n \\ln \\gamma_i = \\ln \\gamma_i^{res} + \\ln \\gamma_i^{comb}\n\n \\ln \\gamma_i^{res} = q_i \\left(1 - \\ln\\frac{\\sum_j^N q_j x_j \\tau_{ji}}\n {\\sum_j^N q_j x_j}- \\sum_j \\frac{q_k x_j \\tau_{ij}}{\\sum_k q_k x_k\n \\tau_{kj}}\\right)\n\n \\ln \\gamma_i^{comb} = (1 - V_i + \\ln V_i) - \\frac{z}{2}q_i\\left(1 -\n \\frac{V_i}{F_i} + \\ln \\frac{V_i}{F_i}\\right)\n\n V_i = \\frac{r_i}{\\sum_j^N r_j x_j}\n\n F_i = \\frac{q_i}{\\sum_j q_j x_j}\n\n Examples\n --------\n Ethanol-water example, at 343.15 K and 1 MPa:\n\n >>> UNIQUAC(xs=[0.252, 0.748], rs=[2.1055, 0.9200], qs=[1.972, 1.400],\n ... taus=[[1.0, 1.0919744384510301], [0.37452902779205477, 1.0]])\n [2.35875137797083, 1.2442093415968987]\n\n References\n ----------\n .. [1] Abrams, Denis S., and John M. Prausnitz. \"Statistical Thermodynamics\n of Liquid Mixtures: A New Expression for the Excess Gibbs Energy of\n Partly or Completely Miscible Systems.\" AIChE Journal 21, no. 1 (January\n 1, 1975): 116-28. doi:10.1002/aic.690210115.\n .. [2] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim:\n Wiley-VCH, 2012.\n .. [3] Maurer, G., and J. M. Prausnitz. \"On the Derivation and Extension of\n the Uniquac Equation.\" Fluid Phase Equilibria 2, no. 2 (January 1,\n 1978): 91-99. doi:10.1016/0378-3812(78)85002-X.\n '''\n cmps = range(len(xs))\n rsxs = sum([rs[i]*xs[i] for i in cmps])\n phis = [rs[i]*xs[i]/rsxs for i in cmps]\n qsxs = sum([qs[i]*xs[i] for i in cmps])\n vs = [qs[i]*xs[i]/qsxs for i in cmps]\n\n Ss = [sum([vs[j]*taus[j][i] for j in cmps]) for i in cmps]\n\n loggammacs = [log(phis[i]/xs[i]) + 1 - phis[i]/xs[i]\n - 5*qs[i]*(log(phis[i]/vs[i]) + 1 - phis[i]/vs[i]) for i in cmps]\n\n loggammars = [qs[i]*(1 - log(Ss[i]) - sum([taus[i][j]*vs[j]/Ss[j]\n for j in cmps])) for i in cmps]\n\n return [exp(loggammacs[i] + loggammars[i]) for i in cmps]", "response": "r Returns the composition of the liquid mixture that is a mixture of the same type as the mixture of the liquid mixture."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef bubble_at_T(zs, Psats, fugacities=None, gammas=None):\n '''\n >>> bubble_at_T([0.5, 0.5], [1400, 7000])\n 4200.0\n >>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75])\n 3395.0\n >>> bubble_at_T([0.5, 0.5], [1400, 7000], gammas=[1.1, .75], fugacities=[.995, 0.98])\n 3452.440775305097\n '''\n if not fugacities:\n fugacities = [1 for i in range(len(Psats))]\n if not gammas:\n gammas = [1 for i in range(len(Psats))]\n if not none_and_length_check((zs, Psats, fugacities, gammas)):\n raise Exception('Input dimentions are inconsistent or some input parameters are missing.')\n P = sum(zs[i]*Psats[i]*gammas[i]/fugacities[i] for i in range(len(zs)))\n return P", "response": "This function calculates the bubble frequency at the given dimentions."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef identify_phase_mixture(T=None, P=None, zs=None, Tcs=None, Pcs=None,\n Psats=None, CASRNs=None,\n AvailableMethods=False, Method=None): # pragma: no cover\n '''\n >>> identify_phase_mixture(T=280, P=5000., zs=[0.5, 0.5], Psats=[1400, 7000])\n ('l', [0.5, 0.5], None, 0)\n >>> identify_phase_mixture(T=280, P=3000., zs=[0.5, 0.5], Psats=[1400, 7000])\n ('two-phase', [0.7142857142857143, 0.2857142857142857], [0.33333333333333337, 0.6666666666666666], 0.5625000000000001)\n >>> identify_phase_mixture(T=280, P=800., zs=[0.5, 0.5], Psats=[1400, 7000])\n ('g', None, [0.5, 0.5], 1)\n >>> identify_phase_mixture(T=280, P=800., zs=[0.5, 0.5])\n (None, None, None, None)\n '''\n def list_methods():\n methods = []\n if Psats and none_and_length_check((Psats, zs)):\n methods.append('IDEAL_VLE')\n if Tcs and none_and_length_check([Tcs]) and all([T >= i for i in Tcs]):\n methods.append('SUPERCRITICAL_T')\n if Pcs and none_and_length_check([Pcs]) and all([P >= i for i in Pcs]):\n methods.append('SUPERCRITICAL_P')\n if Tcs and none_and_length_check([zs, Tcs]) and any([T > Tc for Tc in Tcs]):\n methods.append('IDEAL_VLE_SUPERCRITICAL')\n methods.append('NONE')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n xs, ys, phase, V_over_F = None, None, None, None\n if Method == 'IDEAL_VLE':\n Pdew = dew_at_T(zs, Psats)\n Pbubble = bubble_at_T(zs, Psats)\n if P >= Pbubble:\n phase = 'l'\n ys = None\n xs = zs\n V_over_F = 0\n elif P <= Pdew:\n phase = 'g'\n ys = zs\n xs = None\n V_over_F = 1\n elif Pdew < P < Pbubble:\n xs, ys, V_over_F = flash(P, zs, Psats)\n phase = 'two-phase'\n elif Method == 'SUPERCRITICAL_T':\n if all([T >= i for i in Tcs]):\n phase = 'g'\n else: # The following is nonsensical\n phase = 'two-phase'\n elif Method == 'SUPERCRITICAL_P':\n if all([P >= i for i in Pcs]):\n phase = 'g'\n else: # The following is nonsensical\n phase = 'two-phase'\n elif Method == 'IDEAL_VLE_SUPERCRITICAL':\n Psats = list(Psats)\n for i in range(len(Psats)):\n if not Psats[i] and Tcs[i] and Tcs[i] <= T:\n Psats[i] = 1E8\n Pdew = dew_at_T(zs, Psats)\n Pbubble = 1E99\n if P >= Pbubble:\n phase = 'l'\n ys = None\n xs = zs\n V_over_F = 0\n elif P <= Pdew:\n phase = 'g'\n ys = zs\n xs = None\n V_over_F = 1\n elif Pdew < P < Pbubble:\n xs, ys, V_over_F = flash(P, zs, Psats)\n phase = 'two-phase'\n\n elif Method == 'NONE':\n pass\n else:\n raise Exception('Failure in in function')\n return phase, xs, ys, V_over_F", "response": "Identify the phase of a single object."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Pbubble_mixture(T=None, zs=None, Psats=None, CASRNs=None,\n AvailableMethods=False, Method=None): # pragma: no cover\n '''\n >>> Pbubble_mixture(zs=[0.5, 0.5], Psats=[1400, 7000])\n 4200.0\n '''\n def list_methods():\n methods = []\n if none_and_length_check((Psats, zs)):\n methods.append('IDEAL_VLE')\n methods.append('NONE')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n if Method == 'IDEAL_VLE':\n Pbubble = bubble_at_T(zs, Psats)\n elif Method == 'NONE':\n Pbubble = None\n else:\n raise Exception('Failure in in function')\n return Pbubble", "response": "This function calculates the bubble at T with the given Zs Psats CASRNs and Method."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncalculates the bubble point at a given pressure.", "response": "def bubble_at_P(P, zs, vapor_pressure_eqns, fugacities=None, gammas=None):\n '''Calculates bubble point for a given pressure\n\n Parameters\n ----------\n P : float\n Pressure, [Pa]\n zs : list[float]\n Overall mole fractions of all species, [-]\n vapor_pressure_eqns : list[functions]\n Temperature dependent function for each specie, Returns Psat, [Pa]\n fugacities : list[float], optional\n fugacities of each species, defaults to list of ones, [-]\n gammas : list[float], optional\n gammas of each species, defaults to list of ones, [-]\n\n Returns\n -------\n Tbubble : float, optional\n Temperature of bubble point at pressure `P`, [K]\n\n '''\n\n def bubble_P_error(T):\n Psats = [VP(T) for VP in vapor_pressure_eqns]\n Pcalc = bubble_at_T(zs, Psats, fugacities, gammas)\n\n return P - Pcalc\n\n T_bubble = newton(bubble_P_error, 300)\n\n return T_bubble"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef Pdew_mixture(T=None, zs=None, Psats=None, CASRNs=None,\n AvailableMethods=False, Method=None): # pragma: no cover\n '''\n >>> Pdew_mixture(zs=[0.5, 0.5], Psats=[1400, 7000])\n 2333.3333333333335\n '''\n def list_methods():\n methods = []\n if none_and_length_check((Psats, zs)):\n methods.append('IDEAL_VLE')\n methods.append('NONE')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n if Method == 'IDEAL_VLE':\n Pdew = dew_at_T(zs, Psats)\n elif Method == 'NONE':\n Pdew = None\n else:\n raise Exception('Failure in in function')\n return Pdew", "response": "This function calculates the Pdew of a mixture of the Ideal VLE and a set of CASRNs."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef draw_2d(self, width=300, height=300, Hs=False): # pragma: no cover\n r'''Interface for drawing a 2D image of the molecule.\n Requires an HTML5 browser, and the libraries RDKit and\n IPython. An exception is raised if either of these libraries is\n absent.\n\n Parameters\n ----------\n width : int\n Number of pixels wide for the view\n height : int\n Number of pixels tall for the view\n Hs : bool\n Whether or not to show hydrogen\n\n Examples\n --------\n >>> Chemical('decane').draw_2d() # doctest: +ELLIPSIS\n \n '''\n try:\n from rdkit.Chem import Draw\n from rdkit.Chem.Draw import IPythonConsole\n if Hs:\n mol = self.rdkitmol_Hs\n else:\n mol = self.rdkitmol\n return Draw.MolToImage(mol, size=(width, height))\n except:\n return 'Rdkit is required for this feature.'", "response": "Interface for drawing a 2D image of the molecule."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ninterfacing for drawing an interactive 3D view of the molecule.", "response": "def draw_3d(self, width=300, height=500, style='stick', Hs=True): # pragma: no cover\n r'''Interface for drawing an interactive 3D view of the molecule.\n Requires an HTML5 browser, and the libraries RDKit, pymol3D, and\n IPython. An exception is raised if all three of these libraries are\n not installed.\n\n Parameters\n ----------\n width : int\n Number of pixels wide for the view\n height : int\n Number of pixels tall for the view\n style : str\n One of 'stick', 'line', 'cross', or 'sphere'\n Hs : bool\n Whether or not to show hydrogen\n\n Examples\n --------\n >>> Chemical('cubane').draw_3d()\n \n '''\n try:\n import py3Dmol\n from IPython.display import display\n if Hs:\n mol = self.rdkitmol_Hs\n else:\n mol = self.rdkitmol\n AllChem.EmbedMultipleConfs(mol)\n mb = Chem.MolToMolBlock(mol)\n p = py3Dmol.view(width=width,height=height)\n p.addModel(mb,'sdf')\n p.setStyle({style:{}})\n p.zoomTo()\n display(p.show())\n except:\n return 'py3Dmol, RDKit, and IPython are required for this feature.'"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Um(self):\n r'''Internal energy of the chemical at its current temperature and\n pressure, in units of [J/mol].\n\n This property requires that :obj:`thermo.chemical.set_thermo` ran\n successfully to be accurate.\n It also depends on the molar volume of the chemical at its current\n conditions.\n '''\n return self.Hm - self.P*self.Vm if (self.Vm and self.Hm is not None) else None", "response": "Internal energy of the chemical at its current temperature and\n pressure in units of [ J / mol ]"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn the total energy in units of [ J / mol ]", "response": "def Am(self):\n r'''Helmholtz energy of the chemical at its current temperature and\n pressure, in units of [J/mol].\n\n This property requires that :obj:`thermo.chemical.set_thermo` ran\n successfully to be accurate.\n It also depends on the molar volume of the chemical at its current\n conditions.\n '''\n return self.Um - self.T*self.Sm if (self.Um is not None and self.Sm is not None) else None"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef A(self):\n r'''Helmholtz energy of the chemical at its current temperature and\n pressure, in units of [J/kg].\n\n This property requires that :obj:`thermo.chemical.set_thermo` ran\n successfully to be accurate.\n It also depends on the molar volume of the chemical at its current\n conditions.\n '''\n return self.U - self.T*self.S if (self.U is not None and self.S is not None) else None", "response": "A property that returns the Helmholtz energy of the chemical at its current temperature and\n pressure in units of [ J / k ]."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef charge(self):\n r'''Charge of a chemical, computed with RDKit from a chemical's SMILES.\n If RDKit is not available, holds None.\n\n Examples\n --------\n >>> Chemical('sodium ion').charge\n 1\n '''\n try:\n if not self.rdkitmol:\n return charge_from_formula(self.formula)\n else:\n return Chem.GetFormalCharge(self.rdkitmol)\n except:\n return charge_from_formula(self.formula)", "response": "Returns the charge of a chemical in the SMILES system."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef rdkitmol(self):\n r'''RDKit object of the chemical, without hydrogen. If RDKit is not\n available, holds None.\n\n For examples of what can be done with RDKit, see\n `their website `_.\n '''\n if self.__rdkitmol:\n return self.__rdkitmol\n else:\n try:\n self.__rdkitmol = Chem.MolFromSmiles(self.smiles)\n return self.__rdkitmol\n except:\n return None", "response": "RDKit object of the chemical without hydrogen."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef rdkitmol_Hs(self):\n r'''RDKit object of the chemical, with hydrogen. If RDKit is not\n available, holds None.\n\n For examples of what can be done with RDKit, see\n `their website `_.\n '''\n if self.__rdkitmol_Hs:\n return self.__rdkitmol_Hs\n else:\n try:\n self.__rdkitmol_Hs = Chem.AddHs(self.rdkitmol)\n return self.__rdkitmol_Hs\n except:\n return None", "response": "r'''RDKit object of the chemical with hydrogen."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef atom_fractions(self):\n r'''Dictionary of atom:fractional occurence of the elements in a\n chemical. Useful when performing element balances. For mass-fraction\n occurences, see :obj:`mass_fractions`.\n\n Examples\n --------\n >>> Chemical('Ammonium aluminium sulfate').atom_fractions\n {'H': 0.25, 'S': 0.125, 'Al': 0.0625, 'O': 0.5, 'N': 0.0625}\n '''\n if self.__atom_fractions:\n return self.__atom_fractions\n else:\n self.__atom_fractions = atom_fractions(self.atoms)\n return self.__atom_fractions", "response": "Dictionary of atom : fraction occurence of the elements in a\n chemical. Useful when performing element balances."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef legal_status(self):\n r'''Dictionary of legal status indicators for the chemical.\n\n Examples\n --------\n >>> pprint(Chemical('benzene').legal_status)\n {'DSL': 'LISTED',\n 'EINECS': 'LISTED',\n 'NLP': 'UNLISTED',\n 'SPIN': 'LISTED',\n 'TSCA': 'LISTED'}\n '''\n if self.__legal_status:\n return self.__legal_status\n else:\n self.__legal_status = legal_status(self.CAS, Method='COMBINED')\n return self.__legal_status", "response": "Dictionary of legal status indicators for the chemical."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a dictionary of economic status indicators for the chemical.", "response": "def economic_status(self):\n r'''Dictionary of economic status indicators for the chemical.\n\n Examples\n --------\n >>> pprint(Chemical('benzene').economic_status)\n [\"US public: {'Manufactured': 6165232.1, 'Imported': 463146.474, 'Exported': 271908.252}\",\n u'1,000,000 - 10,000,000 tonnes per annum',\n u'Intermediate Use Only',\n 'OECD HPV Chemicals']\n '''\n if self.__economic_status:\n return self.__economic_status\n else:\n self.__economic_status = economic_status(self.CAS, Method='Combined')\n return self.__economic_status"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef PSRK_groups(self):\n r'''Dictionary of PSRK subgroup: count groups for the PSRK subgroups,\n as determined by `DDBST's online service `_.\n\n Examples\n --------\n >>> pprint(Chemical('Cumene').PSRK_groups)\n {1: 2, 9: 5, 13: 1}\n '''\n if self.__PSRK_groups:\n return self.__PSRK_groups\n else:\n load_group_assignments_DDBST()\n if self.InChI_Key in DDBST_PSRK_assignments:\n self.__PSRK_groups = DDBST_PSRK_assignments[self.InChI_Key]\n return self.__PSRK_groups\n else:\n return None", "response": "Dictionary of PSRK subgroup names for the PSRK subgroups."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning the Hvap property of the chemical at its current temperature.", "response": "def Hvap(self):\n r'''Enthalpy of vaporization of the chemical at its current temperature,\n in units of [J/kg].\n\n This property uses the object-oriented interface\n :obj:`thermo.phase_change.EnthalpyVaporization`, but converts its\n results from molar to mass units.\n\n Examples\n --------\n >>> Chemical('water', T=320).Hvap\n 2389540.219347256\n '''\n Hvamp = self.Hvapm\n if Hvamp:\n return property_molar_to_mass(Hvamp, self.MW)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Cpl(self):\n r'''Liquid-phase heat capacity of the chemical at its current temperature,\n in units of [J/kg/K]. For calculation of this property at other\n temperatures, or specifying manually the method used to calculate it,\n and more - see the object oriented interface\n :obj:`thermo.heat_capacity.HeatCapacityLiquid`; each Chemical instance\n creates one to actually perform the calculations. Note that that\n interface provides output in molar units.\n\n Examples\n --------\n >>> Chemical('water', T=320).Cpl\n 4177.518996988284\n\n Ideal entropy change of water from 280 K to 340 K, output converted\n back to mass-based units of J/kg/K.\n\n >>> dSm = Chemical('water').HeatCapacityLiquid.T_dependent_property_integral_over_T(280, 340)\n >>> property_molar_to_mass(dSm, Chemical('water').MW)\n 812.1024585274956\n '''\n Cplm = self.HeatCapacityLiquid(self.T)\n if Cplm:\n return property_molar_to_mass(Cplm, self.MW)\n return None", "response": "Liquid - phase heat capacity of the chemical at the current temperature."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the property of the chemical at the current temperature and the mass of the chemical at the current temperature.", "response": "def Cpg(self):\n r'''Gas-phase heat capacity of the chemical at its current temperature,\n in units of [J/kg/K]. For calculation of this property at other\n temperatures, or specifying manually the method used to calculate it,\n and more - see the object oriented interface\n :obj:`thermo.heat_capacity.HeatCapacityGas`; each Chemical instance\n creates one to actually perform the calculations. Note that that\n interface provides output in molar units.\n\n Examples\n --------\n >>> w = Chemical('water', T=520)\n >>> w.Cpg\n 1967.6698314620658\n '''\n Cpgm = self.HeatCapacityGas(self.T)\n if Cpgm:\n return property_molar_to_mass(Cpgm, self.MW)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Cvgm(self):\n r'''Gas-phase ideal-gas contant-volume heat capacity of the chemical at\n its current temperature, in units of [J/mol/K]. Subtracts R from\n the ideal-gas heat capacity; does not include pressure-compensation\n from an equation of state.\n\n Examples\n --------\n >>> w = Chemical('water', T=520)\n >>> w.Cvgm\n 27.13366316134193\n '''\n Cpgm = self.HeatCapacityGas(self.T)\n if Cpgm:\n return Cpgm - R\n return None", "response": "Returns the gas - phase ideal - gas contant - volume heat capacity of the chemical at\n s current temperature in units of [ J / mol / K ]."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Cvg(self):\n r'''Gas-phase ideal-gas contant-volume heat capacity of the chemical at\n its current temperature, in units of [J/kg/K]. Subtracts R from\n the ideal-gas heat capacity; does not include pressure-compensation\n from an equation of state.\n\n Examples\n --------\n >>> w = Chemical('water', T=520)\n >>> w.Cvg\n 1506.1471795798861\n '''\n Cvgm = self.Cvgm\n if Cvgm:\n return property_molar_to_mass(Cvgm, self.MW)\n return None", "response": "Returns the chemical contant - volume heat capacity of the chemical at\n ."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef isentropic_exponent(self):\n r'''Gas-phase ideal-gas isentropic exponent of the chemical at its\n current temperature, [dimensionless]. Does not include\n pressure-compensation from an equation of state.\n\n Examples\n --------\n >>> Chemical('hydrogen').isentropic_exponent\n 1.405237786321222\n '''\n Cp, Cv = self.Cpg, self.Cvg\n if all((Cp, Cv)):\n return isentropic_exponent(Cp, Cv)\n return None", "response": "Returns the ideal gas isentropic exponent of the chemical at its\n current temperature."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef rhol(self):\n r'''Liquid-phase mass density of the chemical at its current\n temperature and pressure, in units of [kg/m^3]. For calculation of this\n property at other temperatures and pressures, or specifying manually\n the method used to calculate it, and more - see the object oriented\n interface :obj:`thermo.volume.VolumeLiquid`; each Chemical instance\n creates one to actually perform the calculations. Note that that\n interface provides output in molar units.\n\n Examples\n --------\n >>> Chemical('o-xylene', T=297).rhol\n 876.9946785618097\n '''\n Vml = self.Vml\n if Vml:\n return Vm_to_rho(Vml, self.MW)\n return None", "response": "Returns the liquid mass density of the chemical at its current\n temperature and pressure in units of [ km ]."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef rhog(self):\n r'''Gas-phase mass density of the chemical at its current temperature\n and pressure, in units of [kg/m^3]. For calculation of this property at\n other temperatures or pressures, or specifying manually the method used\n to calculate it, and more - see the object oriented interface\n :obj:`thermo.volume.VolumeGas`; each Chemical instance\n creates one to actually perform the calculations. Note that that\n interface provides output in molar units.\n\n Examples\n --------\n Estimate the density of the core of the sun, at 15 million K and\n 26.5 PetaPascals, assuming pure helium (actually 68% helium):\n\n >>> Chemical('helium', T=15E6, P=26.5E15).rhog\n 8329.27226509739\n\n Compared to a result on\n `Wikipedia `_ of 150000\n kg/m^3, the fundamental equation of state performs poorly.\n\n >>> He = Chemical('helium', T=15E6, P=26.5E15)\n >>> He.VolumeGas.set_user_methods_P(['IDEAL']); He.rhog\n 850477.8065477367\n\n The ideal-gas law performs somewhat better, but vastly overshoots\n the density prediction.\n '''\n Vmg = self.Vmg\n if Vmg:\n return Vm_to_rho(Vmg, self.MW)\n return None", "response": "Returns the gas mass of the chemical at the current temperature and pressure."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Zs(self):\n r'''Compressibility factor of the chemical in the solid phase at the\n current temperature and pressure, [dimensionless].\n\n Utilizes the object oriented interface and\n :obj:`thermo.volume.VolumeSolid` to perform the actual calculation of\n molar volume.\n\n Examples\n --------\n >>> Chemical('palladium').Z\n 0.00036248477437931853\n '''\n Vms = self.Vms\n if Vms:\n return Z(self.T, self.P, Vms)\n return None", "response": "Return the compressibility factor of the chemical in the solid phase at the current temperature and pressure."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Zl(self):\n r'''Compressibility factor of the chemical in the liquid phase at the\n current temperature and pressure, [dimensionless].\n\n Utilizes the object oriented interface and\n :obj:`thermo.volume.VolumeLiquid` to perform the actual calculation of\n molar volume.\n\n Examples\n --------\n >>> Chemical('water').Zl\n 0.0007385375470263454\n '''\n Vml = self.Vml\n if Vml:\n return Z(self.T, self.P, Vml)\n return None", "response": "Return the Zl value of the chemical in the liquid phase at the current temperature and pressure."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef Zg(self):\n r'''Compressibility factor of the chemical in the gas phase at the\n current temperature and pressure, [dimensionless].\n\n Utilizes the object oriented interface and\n :obj:`thermo.volume.VolumeGas` to perform the actual calculation of\n molar volume.\n\n Examples\n --------\n >>> Chemical('sulfur hexafluoride', T=700, P=1E9).Zg\n 11.140084184207813\n '''\n Vmg = self.Vmg\n if Vmg:\n return Z(self.T, self.P, Vmg)\n return None", "response": "Return the compressibility factor of the chemical in the gas phase at the\n current temperature and pressure."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef SGg(self):\n r'''Specific gravity of the gas phase of the chemical, [dimensionless].\n The reference condition is air at 15.6 \u00b0C (60 \u00b0F) and 1 atm \n (rho=1.223 kg/m^3). The definition for gases uses the compressibility\n factor of the reference gas and the chemical both at the reference\n conditions, not the conditions of the chemical.\n \n Examples\n --------\n >>> Chemical('argon').SGg\n 1.3795835970877504\n '''\n Vmg = self.VolumeGas(T=288.70555555555552, P=101325)\n if Vmg:\n rho = Vm_to_rho(Vmg, self.MW)\n return SG(rho, rho_ref=1.2231876628642968) # calculated with Mixture\n return None", "response": "Specific gravity of the gas phase of the chemical."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef API(self):\n r'''API gravity of the liquid phase of the chemical, [degrees].\n The reference condition is water at 15.6 \u00b0C (60 \u00b0F) and 1 atm \n (rho=999.016 kg/m^3, standardized).\n \n Examples\n --------\n >>> Chemical('water').API\n 9.999752435378895\n '''\n Vml = self.VolumeLiquid(T=288.70555555555552, P=101325)\n if Vml:\n rho = Vm_to_rho(Vml, self.MW)\n sg = SG(rho, rho_ref=999.016)\n return SG_to_API(sg)", "response": "A simple API for the chemical."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef Bvirial(self):\n r'''Second virial coefficient of the gas phase of the chemical at its\n current temperature and pressure, in units of [mol/m^3].\n\n This property uses the object-oriented interface\n :obj:`thermo.volume.VolumeGas`, converting its result with\n :obj:`thermo.utils.B_from_Z`.\n\n Examples\n --------\n >>> Chemical('water').Bvirial\n -0.0009596286322838357\n '''\n if self.Vmg:\n return B_from_Z(self.Zg, self.T, self.P)\n return None", "response": "Second virial coefficient of the chemical at its\n current temperature and pressure in units of [mol / m^3 ]"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn the isobaric expansion of the liquid phase of the current cluster.", "response": "def isobaric_expansion_l(self):\n r'''Isobaric (constant-pressure) expansion of the liquid phase of the\n chemical at its current temperature and pressure, in units of [1/K].\n\n .. math::\n \\beta = \\frac{1}{V}\\left(\\frac{\\partial V}{\\partial T} \\right)_P\n\n Utilizes the temperature-derivative method of\n :obj:`thermo.volume.VolumeLiquid` to perform the actual calculation.\n The derivatives are all numerical.\n\n Examples\n --------\n >>> Chemical('dodecane', T=400).isobaric_expansion_l\n 0.0011617555762469477\n '''\n dV_dT = self.VolumeLiquid.TP_dependent_property_derivative_T(self.T, self.P)\n Vm = self.Vml\n if dV_dT and Vm:\n return isobaric_expansion(V=Vm, dV_dT=dV_dT)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef isobaric_expansion_g(self):\n r'''Isobaric (constant-pressure) expansion of the gas phase of the\n chemical at its current temperature and pressure, in units of [1/K].\n\n .. math::\n \\beta = \\frac{1}{V}\\left(\\frac{\\partial V}{\\partial T} \\right)_P\n\n Utilizes the temperature-derivative method of\n :obj:`thermo.VolumeGas` to perform the actual calculation.\n The derivatives are all numerical.\n\n Examples\n --------\n >>> Chemical('Hexachlorobenzene', T=900).isobaric_expansion_g\n 0.001151869741981048\n '''\n dV_dT = self.VolumeGas.TP_dependent_property_derivative_T(self.T, self.P)\n Vm = self.Vmg\n if dV_dT and Vm:\n return isobaric_expansion(V=Vm, dV_dT=dV_dT)", "response": "A simple isobaric expansion of the gas phase of the current chemical at its current temperature and pressure."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn the Joule Thomson coefficient of the chemical in the liquid phase at .", "response": "def JTl(self):\n r'''Joule Thomson coefficient of the chemical in the liquid phase at\n its current temperature and pressure, in units of [K/Pa].\n\n .. math::\n \\mu_{JT} = \\left(\\frac{\\partial T}{\\partial P}\\right)_H = \\frac{1}{C_p}\n \\left[T \\left(\\frac{\\partial V}{\\partial T}\\right)_P - V\\right]\n = \\frac{V}{C_p}\\left(\\beta T-1\\right)\n\n Utilizes the temperature-derivative method of\n :obj:`thermo.volume.VolumeLiquid` and the temperature-dependent heat\n capacity method :obj:`thermo.heat_capacity.HeatCapacityLiquid` to\n obtain the properties required for the actual calculation.\n\n Examples\n --------\n >>> Chemical('dodecane', T=400).JTl\n -3.0827160465192742e-07\n '''\n Vml, Cplm, isobaric_expansion_l = self.Vml, self.Cplm, self.isobaric_expansion_l\n if all((Vml, Cplm, isobaric_expansion_l)):\n return Joule_Thomson(T=self.T, V=Vml, Cp=Cplm, beta=isobaric_expansion_l)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef JTg(self):\n r'''Joule Thomson coefficient of the chemical in the gas phase at\n its current temperature and pressure, in units of [K/Pa].\n\n .. math::\n \\mu_{JT} = \\left(\\frac{\\partial T}{\\partial P}\\right)_H = \\frac{1}{C_p}\n \\left[T \\left(\\frac{\\partial V}{\\partial T}\\right)_P - V\\right]\n = \\frac{V}{C_p}\\left(\\beta T-1\\right)\n\n Utilizes the temperature-derivative method of\n :obj:`thermo.volume.VolumeGas` and the temperature-dependent heat\n capacity method :obj:`thermo.heat_capacity.HeatCapacityGas` to\n obtain the properties required for the actual calculation.\n\n Examples\n --------\n >>> Chemical('dodecane', T=400, P=1000).JTg\n 5.4089897835384913e-05\n '''\n Vmg, Cpgm, isobaric_expansion_g = self.Vmg, self.Cpgm, self.isobaric_expansion_g\n if all((Vmg, Cpgm, isobaric_expansion_g)):\n return Joule_Thomson(T=self.T, V=Vmg, Cp=Cpgm, beta=isobaric_expansion_g)\n return None", "response": "Returns the Joule Thomson coefficient of the chemical in the gas phase at\n ."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the nu of the chemical at its current temperature and pressure in units of [ m^2 / s ].", "response": "def nul(self):\n r'''Kinematic viscosity of the liquid phase of the chemical at its\n current temperature and pressure, in units of [m^2/s].\n\n .. math::\n \\nu = \\frac{\\mu}{\\rho}\n\n Utilizes the temperature and pressure dependent object oriented\n interfaces :obj:`thermo.volume.VolumeLiquid`,\n :obj:`thermo.viscosity.ViscosityLiquid` to calculate the\n actual properties.\n\n Examples\n --------\n >>> Chemical('methane', T=110).nul\n 2.858088468937331e-07\n '''\n mul, rhol = self.mul, self.rhol\n if all([mul, rhol]):\n return nu_mu_converter(mu=mul, rho=rhol)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the nu of the chemical at its current temperature and pressure in units of [ m^2 / s ) if the chemical is in the nug phase otherwise None.", "response": "def nug(self):\n r'''Kinematic viscosity of the gas phase of the chemical at its\n current temperature and pressure, in units of [m^2/s].\n\n .. math::\n \\nu = \\frac{\\mu}{\\rho}\n\n Utilizes the temperature and pressure dependent object oriented\n interfaces :obj:`thermo.volume.VolumeGas`,\n :obj:`thermo.viscosity.ViscosityGas` to calculate the\n actual properties.\n\n Examples\n --------\n >>> Chemical('methane', T=115).nug\n 2.5056924327995865e-06\n '''\n mug, rhog = self.mug, self.rhog\n if all([mug, rhog]):\n return nu_mu_converter(mu=mug, rho=rhog)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef alphal(self):\n r'''Thermal diffusivity of the liquid phase of the chemical at its\n current temperature and pressure, in units of [m^2/s].\n\n .. math::\n \\alpha = \\frac{k}{\\rho Cp}\n\n Utilizes the temperature and pressure dependent object oriented\n interfaces :obj:`thermo.volume.VolumeLiquid`,\n :obj:`thermo.thermal_conductivity.ThermalConductivityLiquid`,\n and :obj:`thermo.heat_capacity.HeatCapacityLiquid` to calculate the\n actual properties.\n\n Examples\n --------\n >>> Chemical('nitrogen', T=70).alphal\n 9.444949636299626e-08\n '''\n kl, rhol, Cpl = self.kl, self.rhol, self.Cpl\n if all([kl, rhol, Cpl]):\n return thermal_diffusivity(k=kl, rho=rhol, Cp=Cpl)\n return None", "response": "Returns the thermal diffusivity of the liquid phase of the chemical at its\n current temperature and pressure in units of [ m^2 / s ]."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef alphag(self):\n r'''Thermal diffusivity of the gas phase of the chemical at its\n current temperature and pressure, in units of [m^2/s].\n\n .. math::\n \\alpha = \\frac{k}{\\rho Cp}\n\n Utilizes the temperature and pressure dependent object oriented\n interfaces :obj:`thermo.volume.VolumeGas`,\n :obj:`thermo.thermal_conductivity.ThermalConductivityGas`,\n and :obj:`thermo.heat_capacity.HeatCapacityGas` to calculate the\n actual properties.\n\n Examples\n --------\n >>> Chemical('ammonia').alphag\n 1.6931865425158556e-05\n '''\n kg, rhog, Cpg = self.kg, self.rhog, self.Cpg\n if all([kg, rhog, Cpg]):\n return thermal_diffusivity(k=kg, rho=rhog, Cp=Cpg)\n return None", "response": "Returns the thermal diffusivity of the gas phase of the chemical at its\n current temperature and pressure in units of [ m^2 / s )."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the Prandtl number of the liquid phase of the chemical at its current temperature and pressure.", "response": "def Prl(self):\n r'''Prandtl number of the liquid phase of the chemical at its\n current temperature and pressure, [dimensionless].\n\n .. math::\n Pr = \\frac{C_p \\mu}{k}\n\n Utilizes the temperature and pressure dependent object oriented\n interfaces :obj:`thermo.viscosity.ViscosityLiquid`,\n :obj:`thermo.thermal_conductivity.ThermalConductivityLiquid`,\n and :obj:`thermo.heat_capacity.HeatCapacityLiquid` to calculate the\n actual properties.\n\n Examples\n --------\n >>> Chemical('nitrogen', T=70).Prl\n 2.7828214501488886\n '''\n Cpl, mul, kl = self.Cpl, self.mul, self.kl\n if all([Cpl, mul, kl]):\n return Prandtl(Cp=Cpl, mu=mul, k=kl)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ncalculating the gas phase of the chemical at its current temperature and pressure and returns the Prandtl number of the gas phase of the chemical at its current temperature and pressure and pressure. Returns None if there is no chemical at its .", "response": "def Prg(self):\n r'''Prandtl number of the gas phase of the chemical at its\n current temperature and pressure, [dimensionless].\n\n .. math::\n Pr = \\frac{C_p \\mu}{k}\n\n Utilizes the temperature and pressure dependent object oriented\n interfaces :obj:`thermo.viscosity.ViscosityGas`,\n :obj:`thermo.thermal_conductivity.ThermalConductivityGas`,\n and :obj:`thermo.heat_capacity.HeatCapacityGas` to calculate the\n actual properties.\n\n Examples\n --------\n >>> Chemical('NH3').Prg\n 0.847263731933008\n '''\n Cpg, mug, kg = self.Cpg, self.mug, self.kg\n if all([Cpg, mug, kg]):\n return Prandtl(Cp=Cpg, mu=mug, k=kg)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the solubility parameter of the chemical at its current temperature and pressure.", "response": "def solubility_parameter(self):\n r'''Solubility parameter of the chemical at its\n current temperature and pressure, in units of [Pa^0.5].\n\n .. math::\n \\delta = \\sqrt{\\frac{\\Delta H_{vap} - RT}{V_m}}\n\n Calculated based on enthalpy of vaporization and molar volume.\n Normally calculated at STP. For uses of this property, see\n :obj:`thermo.solubility.solubility_parameter`.\n\n Examples\n --------\n >>> Chemical('NH3').solubility_parameter\n 24766.329043856073\n '''\n return solubility_parameter(T=self.T, Hvapm=self.Hvapm, Vml=self.Vml,\n Method=self.solubility_parameter_method,\n CASRN=self.CAS)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the mass heat capacity of the chemical at its current phase and the current temperature in units of [ J / kK ].", "response": "def Cp(self):\n r'''Mass heat capacity of the chemical at its current phase and\n temperature, in units of [J/kg/K].\n\n Utilizes the object oriented interfaces\n :obj:`thermo.heat_capacity.HeatCapacitySolid`,\n :obj:`thermo.heat_capacity.HeatCapacityLiquid`,\n and :obj:`thermo.heat_capacity.HeatCapacityGas` to perform the\n actual calculation of each property. Note that those interfaces provide\n output in molar units (J/mol/K).\n\n Examples\n --------\n >>> w = Chemical('water')\n >>> w.Cp, w.phase\n (4180.597021827336, 'l')\n >>> Chemical('palladium').Cp\n 234.26767209171211\n '''\n return phase_select_property(phase=self.phase, s=self.Cps, l=self.Cpl, g=self.Cpg)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Cpm(self):\n r'''Molar heat capacity of the chemical at its current phase and\n temperature, in units of [J/mol/K].\n\n Utilizes the object oriented interfaces\n :obj:`thermo.heat_capacity.HeatCapacitySolid`,\n :obj:`thermo.heat_capacity.HeatCapacityLiquid`,\n and :obj:`thermo.heat_capacity.HeatCapacityGas` to perform the\n actual calculation of each property.\n\n Examples\n --------\n >>> Chemical('cubane').Cpm\n 137.05489206785944\n >>> Chemical('ethylbenzene', T=550, P=3E6).Cpm\n 294.18449553310046\n '''\n return phase_select_property(phase=self.phase, s=self.Cpsm, l=self.Cplm, g=self.Cpgm)", "response": "A method to get the chemical system properties for a given phase."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef rho(self):\n r'''Mass density of the chemical at its current phase and\n temperature and pressure, in units of [kg/m^3].\n\n Utilizes the object oriented interfaces\n :obj:`thermo.volume.VolumeSolid`,\n :obj:`thermo.volume.VolumeLiquid`,\n and :obj:`thermo.volume.VolumeGas` to perform the\n actual calculation of each property. Note that those interfaces provide\n output in units of m^3/mol.\n\n Examples\n --------\n >>> Chemical('decane', T=550, P=2E6).rho\n 498.67008448640604\n '''\n return phase_select_property(phase=self.phase, s=self.rhos, l=self.rhol, g=self.rhog)", "response": "Mass density of the chemical at its current phase and temperature and pressure."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning the Z value of the chemical.", "response": "def Z(self):\n r'''Compressibility factor of the chemical at its current phase and\n temperature and pressure, [dimensionless].\n\n Examples\n --------\n >>> Chemical('MTBE', T=900, P=1E-2).Z\n 0.9999999999079768\n '''\n Vm = self.Vm\n if Vm:\n return Z(self.T, self.P, Vm)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef SG(self):\n r'''Specific gravity of the chemical, [dimensionless]. \n \n For gas-phase conditions, this is calculated at 15.6 \u00b0C (60 \u00b0F) and 1 \n atm for the chemical and the reference fluid, air. \n For liquid and solid phase conditions, this is calculated based on a \n reference fluid of water at 4\u00b0C at 1 atm, but the with the liquid or \n solid chemical's density at the currently specified conditions.\n\n Examples\n --------\n >>> Chemical('MTBE').SG\n 0.7428160596603596\n '''\n phase = self.phase\n if phase == 'l':\n return self.SGl\n elif phase == 's':\n return self.SGs\n elif phase == 'g':\n return self.SGg\n rho = self.rho\n if rho is not None:\n return SG(rho)\n return None", "response": "Returns the SG object for the current state of the object."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the isobaric expansion of the chemical at its current phase and temperature.", "response": "def isobaric_expansion(self):\n r'''Isobaric (constant-pressure) expansion of the chemical at its\n current phase and temperature, in units of [1/K].\n\n .. math::\n \\beta = \\frac{1}{V}\\left(\\frac{\\partial V}{\\partial T} \\right)_P\n\n Examples\n --------\n Radical change in value just above and below the critical temperature\n of water:\n\n >>> Chemical('water', T=647.1, P=22048320.0).isobaric_expansion\n 0.34074205839222449\n\n >>> Chemical('water', T=647.2, P=22048320.0).isobaric_expansion\n 0.18143324022215077\n '''\n return phase_select_property(phase=self.phase, l=self.isobaric_expansion_l, g=self.isobaric_expansion_g)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef mu(self):\n r'''Viscosity of the chemical at its current phase, temperature, and\n pressure in units of [Pa*s].\n\n Utilizes the object oriented interfaces\n :obj:`thermo.viscosity.ViscosityLiquid` and\n :obj:`thermo.viscosity.ViscosityGas` to perform the\n actual calculation of each property.\n\n Examples\n --------\n >>> Chemical('ethanol', T=300).mu\n 0.001044526538460911\n >>> Chemical('ethanol', T=400).mu\n 1.1853097849748217e-05\n '''\n return phase_select_property(phase=self.phase, l=self.mul, g=self.mug)", "response": "Returns the mu of the chemical at the current phase temperature and pressure in units of [ Pa * s )."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef k(self):\n r'''Thermal conductivity of the chemical at its current phase,\n temperature, and pressure in units of [W/m/K].\n\n Utilizes the object oriented interfaces\n :obj:`thermo.thermal_conductivity.ThermalConductivityLiquid` and\n :obj:`thermo.thermal_conductivity.ThermalConductivityGas` to perform\n the actual calculation of each property.\n\n Examples\n --------\n >>> Chemical('ethanol', T=300).kl\n 0.16313594741877802\n >>> Chemical('ethanol', T=400).kg\n 0.026019924109310026\n '''\n return phase_select_property(phase=self.phase, s=None, l=self.kl, g=self.kg)", "response": "Returns the key that identifies the chemical system in which the chemical is in the current phase."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef nu(self):\n r'''Kinematic viscosity of the the chemical at its current temperature,\n pressure, and phase in units of [m^2/s].\n\n .. math::\n \\nu = \\frac{\\mu}{\\rho}\n\n Examples\n --------\n >>> Chemical('argon').nu\n 1.3846930410865003e-05\n '''\n return phase_select_property(phase=self.phase, l=self.nul, g=self.nug)", "response": "Return the nu of the chemical."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Pr(self):\n r'''Prandtl number of the chemical at its current temperature,\n pressure, and phase; [dimensionless].\n\n .. math::\n Pr = \\frac{C_p \\mu}{k}\n\n Examples\n --------\n >>> Chemical('acetone').Pr\n 4.183039103542709\n '''\n return phase_select_property(phase=self.phase, l=self.Prl, g=self.Prg)", "response": "Return the number of the chemical at its current temperature pressure and phase."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Poynting(self):\n r'''Poynting correction factor [dimensionless] for use in phase \n equilibria methods based on activity coefficients or other reference \n states. Performs the shortcut calculation assuming molar volume is \n independent of pressure.\n\n .. math::\n \\text{Poy} = \\exp\\left[\\frac{V_l (P-P^{sat})}{RT}\\right]\n\n The full calculation normally returns values very close to the\n approximate ones. This property is defined in terms of\n pure components only.\n\n Examples\n --------\n >>> Chemical('pentane', T=300, P=1E7).Poynting\n 1.5743051250679803\n\n Notes\n -----\n The full equation shown below can be used as follows:\n\n .. math::\n \\text{Poy} = \\exp\\left[\\frac{\\int_{P_i^{sat}}^P V_i^l dP}{RT}\\right]\n\n >>> from scipy.integrate import quad\n >>> c = Chemical('pentane', T=300, P=1E7)\n >>> exp(quad(lambda P : c.VolumeLiquid(c.T, P), c.Psat, c.P)[0]/R/c.T)\n 1.5821826990975127\n '''\n Vml, Psat = self.Vml, self.Psat\n if Vml and Psat:\n return exp(Vml*(self.P-Psat)/R/self.T)\n return None", "response": "Calculates the Poynting correction factor for use in phase INDRA reference INDRA objects."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef ITS90_68_difference(T):\n r'''Calculates the difference between ITS-90 and ITS-68 scales using a\n series of models listed in [1]_, [2]_, and [3]_.\n\n The temperature difference is given by the following equations:\n\n From 13.8 K to 73.15 K:\n\n .. math::\n T_{90} - T_{68} = a_0 + \\sum_{i=1}^{12} a_i[(T_{90}/K-40)/40]^i\n\n From 83.8 K to 903.75 K:\n\n .. math::\n T_{90} - T_{68} = \\sum_{i=1}^8 b_i[(T_{90}/K - 273.15)/630]^i\n\n From 903.75 K to 1337.33 K:\n\n .. math::\n T_{90} - T_{68} = \\sum_{i=0}^5 c_i[T_{90}/^\\circ C]^i\n\n Above 1337.33 K:\n\n .. math::\n T_{90} - T_{68} = -1.398\\cdot 10^{-7}\\left(\\frac{T_{90}}{K}\\right)^2\n\n\n Parameters\n ----------\n T : float\n Temperature, ITS-90, or approximately ITS-68 [K]\n\n Returns\n -------\n dT : float\n Temperature, difference between ITS-90 and ITS-68 at T [K]\n\n Notes\n -----\n The conversion is straightforward when T90 is known. Theoretically, the\n model should be solved numerically to convert the reverse way. However,\n according to [4]_, the difference is under 0.05 mK from 73.15 K to\n 903.15 K, and under 0.26 mK up to 1337.33 K.\n\n For temperatures under 13.8 K, no conversion is performed.\n\n The first set of coefficients are:\n -0.005903, 0.008174, -0.061924, -0.193388, 1.490793, 1.252347, -9.835868,\n 1.411912, 25.277595, -19.183815, -18.437089, 27.000895, -8.716324.\n\n The second set of coefficients are:\n 0, -0.148759, -0.267408, 1.08076, 1.269056, -4.089591, -1.871251,\n 7.438081, -3.536296.\n\n The third set of coefficients are:\n 7.8687209E1, -4.7135991E-1, 1.0954715E-3, -1.2357884E-6, 6.7736583E-10,\n -1.4458081E-13.\n These last coefficients use the temperature in degrees Celcius. A slightly\n older model used the following coefficients but a different equation over\n the same range:\n -0.00317, -0.97737, 1.2559, 2.03295, -5.91887, -3.23561, 7.23364,\n 5.04151. The model for these coefficients was:\n\n .. math::\n T_{90} - T_{68} = c_0 + \\sum_{i=1}^7 c_i[(T_{90}/K - 1173.15)/300]^i\n\n For temperatures larger than several thousand K, the differences have no\n meaning and grows quadratically.\n\n Examples\n --------\n >>> ITS90_68_difference(1000.)\n 0.01231818956580355\n\n References\n ----------\n .. [1] Bedford, R. E., G. Bonnier, H. Maas, and F. Pavese. \"Techniques for\n Approximating the International Temperature Scale of 1990.\" Bureau\n International Des Poids et Mesures, Sfievres, 1990.\n .. [2] Wier, Ron D., and Robert N. Goldberg. \"On the Conversion of\n Thermodynamic Properties to the Basis of the International Temperature\n Scale of 1990.\" The Journal of Chemical Thermodynamics 28, no. 3\n (March 1996): 261-76. doi:10.1006/jcht.1996.0026.\n .. [3] Goldberg, Robert N., and R. D. Weir. \"Conversion of Temperatures\n and Thermodynamic Properties to the Basis of the International\n Temperature Scale of 1990 (Technical Report).\" Pure and Applied\n Chemistry 64, no. 10 (1992): 1545-1562. doi:10.1351/pac199264101545.\n .. [4] Code10.info. \"Conversions among International Temperature Scales.\"\n Accessed May 22, 2016. http://www.code10.info/index.php%3Foption%3Dcom_content%26view%3Darticle%26id%3D83:conversions-among-international-temperature-scales%26catid%3D60:temperature%26Itemid%3D83.\n '''\n ais = [-0.005903, 0.008174, -0.061924, -0.193388, 1.490793, 1.252347,\n -9.835868, 1.411912, 25.277595, -19.183815, -18.437089, 27.000895,\n -8.716324]\n bis = [0, -0.148759, -0.267408, 1.08076, 1.269056, -4.089591, -1.871251,\n 7.438081, -3.536296]\n# cis = [-0.00317, -0.97737, 1.2559, 2.03295, -5.91887, -3.23561, 7.23364,\n# 5.04151]\n new_cs = [7.8687209E1, -4.7135991E-1, 1.0954715E-3, -1.2357884E-6,\n 6.7736583E-10, -1.4458081E-13]\n dT = 0\n if T < 13.8:\n dT = 0\n elif T >= 13.8 and T <= 73.15:\n for i in range(13):\n dT += ais[i]*((T - 40.)/40.)**i\n elif T > 73.15 and T < 83.8:\n dT = 0\n elif T >= 83.8 and T <= 903.75:\n for i in range(9):\n dT += bis[i]*((T - 273.15)/630.)**i\n elif T > 903.75 and T <= 1337.33:\n # Revised function exists, but does not match the tabulated data\n # for i in range(8):\n # dT += cis[i]*((T - 1173.15)/300.)**i\n for i in range(6):\n dT += new_cs[i]*(T-273.15)**i\n elif T > 1337.33:\n dT = -1.398E-7*T**2\n\n return dT", "response": "r A function that calculates the difference between ITS - 90 and ITS -68 at T."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef GWP(CASRN, AvailableMethods=False, Method=None):\n r'''This function handles the retrieval of a chemical's Global Warming\n Potential, relative to CO2. Lookup is based on CASRNs. Will automatically\n select a data source to use if no Method is provided; returns None if the\n data is not available.\n\n Returns the GWP for the 100yr outlook by default.\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n GWP : float\n Global warming potential, [(impact/mass chemical)/(impact/mass CO2)]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain GWP with the\n given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n The method name to use. Accepted methods are IPCC (2007) 100yr',\n 'IPCC (2007) 100yr-SAR', 'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'. \n All valid values are also held in the list GWP_methods.\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n the GWP for the desired chemical, and will return methods\n instead of the GWP\n\n Notes\n -----\n All data is from [1]_, the official source. Several chemicals are available\n in [1]_ are not included here as they do not have a CAS.\n Methods are 'IPCC (2007) 100yr', 'IPCC (2007) 100yr-SAR',\n 'IPCC (2007) 20yr', and 'IPCC (2007) 500yr'.\n\n Examples\n --------\n Methane, 100-yr outlook\n\n >>> GWP(CASRN='74-82-8')\n 25.0\n\n References\n ----------\n .. [1] IPCC. \"2.10.2 Direct Global Warming Potentials - AR4 WGI Chapter 2:\n Changes in Atmospheric Constituents and in Radiative Forcing.\" 2007.\n https://www.ipcc.ch/publications_and_data/ar4/wg1/en/ch2s2-10-2.html.\n '''\n def list_methods():\n methods = []\n if CASRN in GWP_data.index:\n methods.append(IPCC100)\n if not pd.isnull(GWP_data.at[CASRN, 'SAR 100yr']):\n methods.append(IPCC100SAR)\n methods.append(IPCC20)\n methods.append(IPCC500)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == IPCC100:\n return float(GWP_data.at[CASRN, '100yr GWP'])\n elif Method == IPCC100SAR:\n return float(GWP_data.at[CASRN, 'SAR 100yr'])\n elif Method == IPCC20:\n return float(GWP_data.at[CASRN, '20yr GWP'])\n elif Method == IPCC500:\n return float(GWP_data.at[CASRN, '500yr GWP'])\n elif Method == NONE:\n return None\n else:\n raise Exception('Failure in in function')", "response": "r Returns the GWP for the given CASRN."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef ODP(CASRN, AvailableMethods=False, Method=None):\n r'''This function handles the retrieval of a chemical's Ozone Depletion\n Potential, relative to CFC-11 (trichlorofluoromethane). Lookup is based on\n CASRNs. Will automatically select a data source to use if no Method is\n provided; returns None if the data is not available.\n\n Returns the ODP of a chemical according to [2]_ when a method is not\n specified. If a range is provided in [2]_, the highest value is returned.\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n ODP : float or str\n Ozone Depletion potential, [(impact/mass chemical)/(impact/mass CFC-11)];\n if method selected has `string` in it, this will be returned as a\n string regardless of if a range is given or a number\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain ODP with the\n given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n The method name to use. Accepted methods are 'ODP2 Max', 'ODP2 Min', \n 'ODP2 string', 'ODP2 logarithmic average', and methods for older values\n are 'ODP1 Max', 'ODP1 Min', 'ODP1 string', and 'ODP1 logarithmic average'.\n All valid values are also held in the list ODP_methods.\n Method : string, optional\n A string for the method name to use, as defined by constants in\n ODP_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n the ODP for the desired chemical, and will return methods\n instead of the ODP\n\n Notes\n -----\n Values are tabulated only for a small number of halogenated hydrocarbons,\n responsible for the largest impact. The original values of ODP as defined\n in the Montreal Protocol are also available, as methods with the `ODP1`\n prefix.\n\n All values are somewhat emperical, as actual reaction rates of chemicals\n with ozone depend on temperature which depends on latitude, longitude,\n time of day, weather, and the concentrations of other pollutants.\n\n All data is from [1]_. Several mixtures listed in [1]_ are not included\n here as they are not pure species.\n Methods for values in [2]_ are 'ODP2 Max', 'ODP2 Min', 'ODP2 string',\n 'ODP2 logarithmic average', and methods for older values are 'ODP1 Max',\n 'ODP1 Min', 'ODP1 string', and 'ODP1 logarithmic average'.\n\n Examples\n --------\n Dichlorotetrafluoroethane, according to [2]_.\n\n >>> ODP(CASRN='76-14-2')\n 0.58\n\n References\n ----------\n .. [1] US EPA, OAR. \"Ozone-Depleting Substances.\" Accessed April 26, 2016.\n https://www.epa.gov/ozone-layer-protection/ozone-depleting-substances.\n .. [2] WMO (World Meteorological Organization), 2011: Scientific Assessment\n of Ozone Depletion: 2010. Global Ozone Research and Monitoring\n Project-Report No. 52, Geneva, Switzerland, 516 p.\n https://www.wmo.int/pages/prog/arep/gaw/ozone_2010/documents/Ozone-Assessment-2010-complete.pdf\n '''\n def list_methods():\n methods = []\n if CASRN in ODP_data.index:\n if not pd.isnull(ODP_data.at[CASRN, 'ODP2 Max']):\n methods.append(ODP2MAX)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP1 Max']):\n methods.append(ODP1MAX)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP2 Design']):\n methods.append(ODP2LOG)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP1 Design']):\n methods.append(ODP1LOG)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP2 Min']):\n methods.append(ODP2MIN)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP1 Min']):\n methods.append(ODP1MIN)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP2']):\n methods.append(ODP2STR)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP1']):\n methods.append(ODP1STR)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == ODP2MAX:\n return float(ODP_data.at[CASRN, 'ODP2 Max'])\n elif Method == ODP1MAX:\n return float(ODP_data.at[CASRN, 'ODP1 Max'])\n elif Method == ODP2MIN:\n return float(ODP_data.at[CASRN, 'ODP2 Min'])\n elif Method == ODP1MIN:\n return float(ODP_data.at[CASRN, 'ODP1 Min'])\n elif Method == ODP2LOG:\n return float(ODP_data.at[CASRN, 'ODP2 Design'])\n elif Method == ODP1LOG:\n return float(ODP_data.at[CASRN, 'ODP1 Design'])\n elif Method == ODP2STR:\n return str(ODP_data.at[CASRN, 'ODP2'])\n elif Method == ODP1STR:\n return str(ODP_data.at[CASRN, 'ODP1'])\n elif Method == NONE:\n return None\n else:\n raise Exception('Failure in in function')", "response": "r Returns the ODP of a chemical with the given CASRN."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef TRC_Antoine_extended(T, Tc, to, A, B, C, n, E, F):\n r'''Calculates vapor pressure of a chemical using the TRC Extended Antoine\n equation. Parameters are chemical dependent, and said to be from the \n Thermodynamics Research Center (TRC) at Texas A&M. Coefficients for various\n chemicals can be found in [1]_.\n\n .. math::\n \\log_{10} P^{sat} = A - \\frac{B}{T + C} + 0.43429x^n + Ex^8 + Fx^{12}\n \n x = \\max \\left(\\frac{T-t_o-273.15}{T_c}, 0 \\right)\n\n Parameters\n ----------\n T : float\n Temperature of fluid, [K]\n A, B, C, n, E, F : floats\n Regressed coefficients for the Antoine Extended (TRC) equation,\n specific for each chemical, [-]\n\n Returns\n -------\n Psat : float\n Vapor pressure calculated with coefficients [Pa]\n \n Notes\n -----\n Assumes coefficients are for calculating vapor pressure in Pascal. \n Coefficients should be consistent with input temperatures in Kelvin;\n\n Examples\n --------\n Tetrafluoromethane, coefficients from [1]_, at 180 K:\n \n >>> TRC_Antoine_extended(180.0, 227.51, -120., 8.95894, 510.595, -15.95, \n ... 2.41377, -93.74, 7425.9) \n 706317.0898414153\n\n References\n ----------\n .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n '''\n x = max((T - to - 273.15)/Tc, 0.)\n return 10.**(A - B/(T+C) + 0.43429*x**n + E*x**8 + F*x**12)", "response": "r Calculates the vapor pressure of a Tetra - Fluoromethane in the Antoine Extended system."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef Wagner_original(T, Tc, Pc, a, b, c, d):\n r'''Calculates vapor pressure using the Wagner equation (3, 6 form).\n\n Requires critical temperature and pressure as well as four coefficients\n specific to each chemical.\n\n .. math::\n \\ln P^{sat}= \\ln P_c + \\frac{a\\tau + b \\tau^{1.5} + c\\tau^3 + d\\tau^6}\n {T_r}\n \n \\tau = 1 - \\frac{T}{T_c}\n\n Parameters\n ----------\n T : float\n Temperature of fluid, [K]\n Tc : float\n Critical temperature, [K]\n Pc : float\n Critical pressure, [Pa]\n a, b, c, d : floats\n Parameters for wagner equation. Specific to each chemical. [-]\n\n Returns\n -------\n Psat : float\n Vapor pressure at T [Pa]\n\n Notes\n -----\n Warning: Pc is often treated as adjustable constant.\n\n Examples\n --------\n Methane, coefficients from [2]_, at 100 K.\n\n >>> Wagner_original(100.0, 190.53, 4596420., a=-6.00435, b=1.1885, \n ... c=-0.834082, d=-1.22833)\n 34520.44601450496\n\n References\n ----------\n .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n .. [2] McGarry, Jack. \"Correlation and Prediction of the Vapor Pressures of\n Pure Liquids over Large Pressure Ranges.\" Industrial & Engineering\n Chemistry Process Design and Development 22, no. 2 (April 1, 1983):\n 313-22. doi:10.1021/i200021a023.\n '''\n Tr = T/Tc\n tau = 1.0 - Tr\n return Pc*exp((a*tau + b*tau**1.5 + c*tau**3 + d*tau**6)/Tr)", "response": "A function that calculates the vapor pressure using the Wagner equation."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef boiling_critical_relation(T, Tb, Tc, Pc):\n r'''Calculates vapor pressure of a fluid at arbitrary temperatures using a\n CSP relationship as in [1]_; requires a chemical's critical temperature\n and pressure as well as boiling point.\n\n The vapor pressure is given by:\n\n .. math::\n \\ln P^{sat}_r = h\\left( 1 - \\frac{1}{T_r}\\right)\n\n h = T_{br} \\frac{\\ln(P_c/101325)}{1-T_{br}}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tb : float\n Boiling temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n\n Returns\n -------\n Psat : float\n Vapor pressure at T [Pa]\n\n Notes\n -----\n Units are Pa. Formulation makes intuitive sense; a logarithmic form of\n interpolation.\n\n Examples\n --------\n Example as in [1]_ for ethylbenzene\n\n >>> boiling_critical_relation(347.2, 409.3, 617.1, 36E5)\n 15209.467273093938\n\n References\n ----------\n .. [1] Reid, Robert C..; Prausnitz, John M.;; Poling, Bruce E.\n The Properties of Gases and Liquids. McGraw-Hill Companies, 1987.\n '''\n Tbr = Tb/Tc\n Tr = T/Tc\n h = Tbr*log(Pc/101325.)/(1 - Tbr)\n return exp(h*(1-1/Tr))*Pc", "response": "r Calculates the vapor pressure of a single local system at arbitrary temperatures using a chemical s critical temperature and pressure as well as boiling point."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Ambrose_Walton(T, Tc, Pc, omega):\n r'''Calculates vapor pressure of a fluid at arbitrary temperatures using a\n CSP relationship by [1]_; requires a chemical's critical temperature and\n acentric factor.\n\n The vapor pressure is given by:\n\n .. math::\n \\ln P_r=f^{(0)}+\\omega f^{(1)}+\\omega^2f^{(2)}\n\n f^{(0)}=\\frac{-5.97616\\tau + 1.29874\\tau^{1.5}- 0.60394\\tau^{2.5}\n -1.06841\\tau^5}{T_r}\n\n f^{(1)}=\\frac{-5.03365\\tau + 1.11505\\tau^{1.5}- 5.41217\\tau^{2.5}\n -7.46628\\tau^5}{T_r}\n\n f^{(2)}=\\frac{-0.64771\\tau + 2.41539\\tau^{1.5}- 4.26979\\tau^{2.5}\n +3.25259\\tau^5}{T_r}\n\n \\tau = 1-T_{r}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n omega : float\n Acentric factor [-]\n\n Returns\n -------\n Psat : float\n Vapor pressure at T [Pa]\n\n Notes\n -----\n Somewhat more accurate than the :obj:`Lee_Kesler` formulation.\n\n Examples\n --------\n Example from [2]_; ethylbenzene at 347.25 K.\n\n >>> Ambrose_Walton(347.25, 617.15, 36.09E5, 0.304)\n 13278.878504306222\n\n References\n ----------\n .. [1] Ambrose, D., and J. Walton. \"Vapour Pressures up to Their Critical\n Temperatures of Normal Alkanes and 1-Alkanols.\" Pure and Applied\n Chemistry 61, no. 8 (1989): 1395-1403. doi:10.1351/pac198961081395.\n .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n '''\n Tr = T/Tc\n tau = 1 - T/Tc\n f0 = (-5.97616*tau + 1.29874*tau**1.5 - 0.60394*tau**2.5 - 1.06841*tau**5)/Tr\n f1 = (-5.03365*tau + 1.11505*tau**1.5 - 5.41217*tau**2.5 - 7.46628*tau**5)/Tr\n f2 = (-0.64771*tau + 2.41539*tau**1.5 - 4.26979*tau**2.5 + 3.25259*tau**5)/Tr\n return Pc*exp(f0 + omega*f1 + omega**2*f2)", "response": "A function that calculates the vapor pressure of a single class in a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Sanjari(T, Tc, Pc, omega):\n r'''Calculates vapor pressure of a fluid at arbitrary temperatures using a\n CSP relationship by [1]_. Requires a chemical's critical temperature,\n pressure, and acentric factor. Although developed for refrigerants,\n this model should have some general predictive ability.\n\n The vapor pressure of a chemical at `T` is given by:\n\n .. math::\n P^{sat} = P_c\\exp(f^{(0)} + \\omega f^{(1)} + \\omega^2 f^{(2)})\n\n f^{(0)} = a_1 + \\frac{a_2}{T_r} + a_3\\ln T_r + a_4 T_r^{1.9}\n\n f^{(1)} = a_5 + \\frac{a_6}{T_r} + a_7\\ln T_r + a_8 T_r^{1.9}\n\n f^{(2)} = a_9 + \\frac{a_{10}}{T_r} + a_{11}\\ln T_r + a_{12} T_r^{1.9}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n omega : float\n Acentric factor [-]\n\n Returns\n -------\n Psat : float\n Vapor pressure, [Pa]\n\n Notes\n -----\n a[1-12] are as follows:\n 6.83377, -5.76051, 0.90654, -1.16906,\n 5.32034, -28.1460, -58.0352, 23.57466,\n 18.19967, 16.33839, 65.6995, -35.9739.\n\n For a claimed fluid not included in the regression, R128, the claimed AARD\n was 0.428%. A re-calculation using 200 data points from 125.45 K to\n 343.90225 K evenly spaced by 1.09775 K as generated by NIST Webbook April\n 2016 produced an AARD of 0.644%. It is likely that the author's regression\n used more precision in its coefficients than was shown here. Nevertheless,\n the function is reproduced as shown in [1]_.\n\n For Tc=808 K, Pc=1100000 Pa, omega=1.1571, this function actually declines\n after 770 K.\n\n Examples\n --------\n >>> Sanjari(347.2, 617.1, 36E5, 0.299)\n 13651.916109552498\n\n References\n ----------\n .. [1] Sanjari, Ehsan, Mehrdad Honarmand, Hamidreza Badihi, and Ali\n Ghaheri. \"An Accurate Generalized Model for Predict Vapor Pressure of\n Refrigerants.\" International Journal of Refrigeration 36, no. 4\n (June 2013): 1327-32. doi:10.1016/j.ijrefrig.2013.01.007.\n '''\n Tr = T/Tc\n f0 = 6.83377 + -5.76051/Tr + 0.90654*log(Tr) + -1.16906*Tr**1.9\n f1 = 5.32034 + -28.1460/Tr + -58.0352*log(Tr) + 23.57466*Tr**1.9\n f2 = 18.19967 + 16.33839/Tr + 65.6995*log(Tr) + -35.9739*Tr**1.9\n return Pc*exp(f0 + omega*f1 + omega**2*f2)", "response": "r Sanjari model for the base class."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Edalat(T, Tc, Pc, omega):\n r'''Calculates vapor pressure of a fluid at arbitrary temperatures using a\n CSP relationship by [1]_. Requires a chemical's critical temperature,\n pressure, and acentric factor. Claimed to have a higher accuracy than the\n Lee-Kesler CSP relationship.\n\n The vapor pressure of a chemical at `T` is given by:\n\n .. math::\n \\ln(P^{sat}/P_c) = \\frac{a\\tau + b\\tau^{1.5} + c\\tau^3 + d\\tau^6}\n {1-\\tau}\n \n a = -6.1559 - 4.0855\\omega\n \n b = 1.5737 - 1.0540\\omega - 4.4365\\times 10^{-3} d\n \n c = -0.8747 - 7.8874\\omega\n \n d = \\frac{1}{-0.4893 - 0.9912\\omega + 3.1551\\omega^2}\n \n \\tau = 1 - \\frac{T}{T_c}\n \n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n omega : float\n Acentric factor [-]\n\n Returns\n -------\n Psat : float\n Vapor pressure, [Pa]\n\n Notes\n -----\n [1]_ found an average error of 6.06% on 94 compounds and 1106 data points.\n \n Examples\n --------\n >>> Edalat(347.2, 617.1, 36E5, 0.299)\n 13461.273080743307\n\n References\n ----------\n .. [1] Edalat, M., R. B. Bozar-Jomehri, and G. A. Mansoori. \"Generalized \n Equation Predicts Vapor Pressure of Hydrocarbons.\" Oil and Gas Journal; \n 91:5 (February 1, 1993).\n '''\n tau = 1. - T/Tc\n a = -6.1559 - 4.0855*omega\n c = -0.8747 - 7.8874*omega\n d = 1./(-0.4893 - 0.9912*omega + 3.1551*omega**2)\n b = 1.5737 - 1.0540*omega - 4.4365E-3*d\n lnPr = (a*tau + b*tau**1.5 + c*tau**3 + d*tau**6)/(1.-tau)\n return exp(lnPr)*Pc", "response": "r Returns a base class that calculates the vapor pressure of a chemical at arbitrary temperatures using the Lee - Kesler CSP relationship."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef check_sufficient_inputs(self):\n '''Method to an exception if none of the pairs (T, P), (T, V), or \n (P, V) are given. '''\n if not ((self.T and self.P) or (self.T and self.V) or (self.P and self.V)):\n raise Exception('Either T and P, or T and V, or P and V are required')", "response": "Method to an exception if neither T P or V are given."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsolving for a single species.", "response": "def solve(self):\n '''First EOS-generic method; should be called by all specific EOSs.\n For solving for `T`, the EOS must provide the method `solve_T`.\n For all cases, the EOS must provide `a_alpha_and_derivatives`.\n Calls `set_from_PT` once done.\n '''\n self.check_sufficient_inputs()\n \n if self.V:\n if self.P:\n self.T = self.solve_T(self.P, self.V)\n self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2 = self.a_alpha_and_derivatives(self.T)\n else:\n self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2 = self.a_alpha_and_derivatives(self.T)\n self.P = R*self.T/(self.V-self.b) - self.a_alpha/(self.V*self.V + self.delta*self.V + self.epsilon)\n Vs = [self.V, 1j, 1j]\n else:\n self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2 = self.a_alpha_and_derivatives(self.T)\n Vs = self.volume_solutions(self.T, self.P, self.b, self.delta, self.epsilon, self.a_alpha)\n self.set_from_PT(Vs)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncounts the number of real volumes in `Vs`, and determines what to do. If there is only one real volume, the method `set_properties_from_solution` is called with it. If there are two real volumes, `set_properties_from_solution` is called once with each volume. The phase is returned by `set_properties_from_solution`, and the volumes is set to either `V_l` or `V_g` as appropriate. Parameters ---------- Vs : list[float] Three possible molar volumes, [m^3/mol]", "response": "def set_from_PT(self, Vs):\n '''Counts the number of real volumes in `Vs`, and determines what to do.\n If there is only one real volume, the method \n `set_properties_from_solution` is called with it. If there are\n two real volumes, `set_properties_from_solution` is called once with \n each volume. The phase is returned by `set_properties_from_solution`, \n and the volumes is set to either `V_l` or `V_g` as appropriate. \n\n Parameters\n ----------\n Vs : list[float]\n Three possible molar volumes, [m^3/mol]\n '''\n # All roots will have some imaginary component; ignore them if > 1E-9\n good_roots = []\n bad_roots = []\n for i in Vs:\n j = i.real\n if abs(i.imag) > 1E-9 or j < 0:\n bad_roots.append(i)\n else:\n good_roots.append(j)\n \n if len(bad_roots) == 2: \n V = good_roots[0]\n self.phase = self.set_properties_from_solution(self.T, self.P, V, self.b, self.delta, self.epsilon, self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2)\n if self.phase == 'l':\n self.V_l = V\n else:\n self.V_g = V\n else:\n # Even in the case of three real roots, it is still the min/max that make sense\n self.V_l, self.V_g = min(good_roots), max(good_roots)\n [self.set_properties_from_solution(self.T, self.P, V, self.b, self.delta, self.epsilon, self.a_alpha, self.da_alpha_dT, self.d2a_alpha_dT2) for V in [self.V_l, self.V_g]]\n self.phase = 'l/g'"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef set_properties_from_solution(self, T, P, V, b, delta, epsilon, a_alpha, \n da_alpha_dT, d2a_alpha_dT2, quick=True):\n r'''Sets all interesting properties which can be calculated from an\n EOS alone. Determines which phase the fluid is on its own; for details,\n see `phase_identification_parameter`.\n \n The list of properties set is as follows, with all properties suffixed\n with '_l' or '_g'.\n \n dP_dT, dP_dV, dV_dT, dV_dP, dT_dV, dT_dP, d2P_dT2, d2P_dV2, d2V_dT2, \n d2V_dP2, d2T_dV2, d2T_dP2, d2V_dPdT, d2P_dTdV, d2T_dPdV, H_dep, S_dep, \n beta, kappa, Cp_minus_Cv, V_dep, U_dep, G_dep, A_dep, fugacity, phi, \n and PIP.\n\n Parameters\n ----------\n T : float\n Temperature, [K]\n P : float\n Pressure, [Pa]\n V : float\n Molar volume, [m^3/mol]\n b : float\n Coefficient calculated by EOS-specific method, [m^3/mol]\n delta : float\n Coefficient calculated by EOS-specific method, [m^3/mol]\n epsilon : float\n Coefficient calculated by EOS-specific method, [m^6/mol^2]\n a_alpha : float\n Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa]\n da_alpha_dT : float\n Temperature derivative of coefficient calculated by EOS-specific \n method, [J^2/mol^2/Pa/K]\n d2a_alpha_dT2 : float\n Second temperature derivative of coefficient calculated by \n EOS-specific method, [J^2/mol^2/Pa/K**2]\n quick : bool, optional\n Whether to use a SymPy cse-derived expression (3x faster) or \n individual formulas\n \n Returns\n -------\n phase : str\n Either 'l' or 'g'\n \n Notes\n -----\n The individual formulas for the derivatives and excess properties are \n as follows. For definitions of `beta`, see `isobaric_expansion`;\n for `kappa`, see isothermal_compressibility; for `Cp_minus_Cv`, see\n `Cp_minus_Cv`; for `phase_identification_parameter`, see \n `phase_identification_parameter`.\n \n First derivatives; in part using the Triple Product Rule [2]_, [3]_:\n \n .. math::\n \\left(\\frac{\\partial P}{\\partial T}\\right)_V = \\frac{R}{V - b}\n - \\frac{a \\frac{d \\alpha{\\left (T \\right )}}{d T}}{V^{2} + V \\delta\n + \\epsilon}\n \n \\left(\\frac{\\partial P}{\\partial V}\\right)_T = - \\frac{R T}{\\left(\n V - b\\right)^{2}} - \\frac{a \\left(- 2 V - \\delta\\right) \\alpha{\n \\left (T \\right )}}{\\left(V^{2} + V \\delta + \\epsilon\\right)^{2}}\n \n \\left(\\frac{\\partial V}{\\partial T}\\right)_P =-\\frac{\n \\left(\\frac{\\partial P}{\\partial T}\\right)_V}{\n \\left(\\frac{\\partial P}{\\partial V}\\right)_T}\n \n \\left(\\frac{\\partial V}{\\partial P}\\right)_T =-\\frac{\n \\left(\\frac{\\partial V}{\\partial T}\\right)_P}{\n \\left(\\frac{\\partial P}{\\partial T}\\right)_V} \n\n \\left(\\frac{\\partial T}{\\partial V}\\right)_P = \\frac{1}\n {\\left(\\frac{\\partial V}{\\partial T}\\right)_P}\n \n \\left(\\frac{\\partial T}{\\partial P}\\right)_V = \\frac{1}\n {\\left(\\frac{\\partial P}{\\partial T}\\right)_V}\n \n Second derivatives with respect to one variable; those of `T` and `V`\n use identities shown in [1]_ and verified numerically:\n \n .. math::\n \\left(\\frac{\\partial^2 P}{\\partial T^2}\\right)_V = - \\frac{a \n \\frac{d^{2} \\alpha{\\left (T \\right )}}{d T^{2}}}{V^{2} + V \\delta \n + \\epsilon}\n \n \\left(\\frac{\\partial^2 P}{\\partial V^2}\\right)_T = 2 \\left(\\frac{\n R T}{\\left(V - b\\right)^{3}} - \\frac{a \\left(2 V + \\delta\\right)^{\n 2} \\alpha{\\left (T \\right )}}{\\left(V^{2} + V \\delta + \\epsilon\n \\right)^{3}} + \\frac{a \\alpha{\\left (T \\right )}}{\\left(V^{2} + V \n \\delta + \\epsilon\\right)^{2}}\\right)\n \n \\left(\\frac{\\partial^2 T}{\\partial P^2}\\right)_V = -\\left(\\frac{\n \\partial^2 P}{\\partial T^2}\\right)_V \\left(\\frac{\\partial P}{\n \\partial T}\\right)^{-3}_V\n \n \\left(\\frac{\\partial^2 V}{\\partial P^2}\\right)_T = -\\left(\\frac{\n \\partial^2 P}{\\partial V^2}\\right)_T \\left(\\frac{\\partial P}{\n \\partial V}\\right)^{-3}_T\n \n \\left(\\frac{\\partial^2 T}{\\partial V^2}\\right)_P = -\\left[\n \\left(\\frac{\\partial^2 P}{\\partial V^2}\\right)_T\n \\left(\\frac{\\partial P}{\\partial T}\\right)_V\n - \\left(\\frac{\\partial P}{\\partial V}\\right)_T\n \\left(\\frac{\\partial^2 P}{\\partial T \\partial V}\\right) \\right]\n \\left(\\frac{\\partial P}{\\partial T}\\right)^{-2}_V\n + \\left[\\left(\\frac{\\partial^2 P}{\\partial T\\partial V}\\right)\n \\left(\\frac{\\partial P}{\\partial T}\\right)_V \n - \\left(\\frac{\\partial P}{\\partial V}\\right)_T\n \\left(\\frac{\\partial^2 P}{\\partial T^2}\\right)_V\\right]\n \\left(\\frac{\\partial P}{\\partial T}\\right)_V^{-3}\n \\left(\\frac{\\partial P}{\\partial V}\\right)_T\n\n \\left(\\frac{\\partial^2 V}{\\partial T^2}\\right)_P = -\\left[\n \\left(\\frac{\\partial^2 P}{\\partial T^2}\\right)_V\n \\left(\\frac{\\partial P}{\\partial V}\\right)_T\n - \\left(\\frac{\\partial P}{\\partial T}\\right)_V\n \\left(\\frac{\\partial^2 P}{\\partial T \\partial V}\\right) \\right]\n \\left(\\frac{\\partial P}{\\partial V}\\right)^{-2}_T\n + \\left[\\left(\\frac{\\partial^2 P}{\\partial T\\partial V}\\right)\n \\left(\\frac{\\partial P}{\\partial V}\\right)_T \n - \\left(\\frac{\\partial P}{\\partial T}\\right)_V\n \\left(\\frac{\\partial^2 P}{\\partial V^2}\\right)_T\\right]\n \\left(\\frac{\\partial P}{\\partial V}\\right)_T^{-3}\n \\left(\\frac{\\partial P}{\\partial T}\\right)_V\n\n \n Second derivatives with respect to the other two variables; those of \n `T` and `V` use identities shown in [1]_ and verified numerically:\n\n .. math::\n \\left(\\frac{\\partial^2 P}{\\partial T \\partial V}\\right) = - \\frac{\n R}{\\left(V - b\\right)^{2}} + \\frac{a \\left(2 V + \\delta\\right) \n \\frac{d \\alpha{\\left (T \\right )}}{d T}}{\\left(V^{2} + V \\delta \n + \\epsilon\\right)^{2}}\n \n \\left(\\frac{\\partial^2 T}{\\partial P\\partial V}\\right) = \n - \\left[\\left(\\frac{\\partial^2 P}{\\partial T \\partial V}\\right)\n \\left(\\frac{\\partial P}{\\partial T}\\right)_V\n - \\left(\\frac{\\partial P}{\\partial V}\\right)_T\n \\left(\\frac{\\partial^2 P}{\\partial T^2}\\right)_V\n \\right]\\left(\\frac{\\partial P}{\\partial T}\\right)_V^{-3}\n\n \\left(\\frac{\\partial^2 V}{\\partial T\\partial P}\\right) = \n - \\left[\\left(\\frac{\\partial^2 P}{\\partial T \\partial V}\\right)\n \\left(\\frac{\\partial P}{\\partial V}\\right)_T\n - \\left(\\frac{\\partial P}{\\partial T}\\right)_V\n \\left(\\frac{\\partial^2 P}{\\partial V^2}\\right)_T\n \\right]\\left(\\frac{\\partial P}{\\partial V}\\right)_T^{-3}\n\n Excess properties\n \n .. math::\n H_{dep} = \\int_{\\infty}^V \\left[T\\frac{\\partial P}{\\partial T}_V \n - P\\right]dV + PV - RT= P V - R T + \\frac{2}{\\sqrt{\n \\delta^{2} - 4 \\epsilon}} \\left(T a \\frac{d \\alpha{\\left (T \\right \n )}}{d T} - a \\alpha{\\left (T \\right )}\\right) \\operatorname{atanh}\n {\\left (\\frac{2 V + \\delta}{\\sqrt{\\delta^{2} - 4 \\epsilon}} \n \\right)}\n\n S_{dep} = \\int_{\\infty}^V\\left[\\frac{\\partial P}{\\partial T} \n - \\frac{R}{V}\\right] dV + R\\log\\frac{PV}{RT} = - R \\log{\\left (V \n \\right )} + R \\log{\\left (\\frac{P V}{R T} \\right )} + R \\log{\\left\n (V - b \\right )} + \\frac{2 a \\frac{d\\alpha{\\left (T \\right )}}{d T}\n }{\\sqrt{\\delta^{2} - 4 \\epsilon}} \\operatorname{atanh}{\\left (\\frac\n {2 V + \\delta}{\\sqrt{\\delta^{2} - 4 \\epsilon}} \\right )}\n \n V_{dep} = V - \\frac{RT}{P}\n \n U_{dep} = H_{dep} - P V_{dep}\n \n G_{dep} = H_{dep} - T S_{dep}\n \n A_{dep} = U_{dep} - T S_{dep}\n \n \\text{fugacity} = P\\exp\\left(\\frac{G_{dep}}{RT}\\right)\n \n \\phi = \\frac{\\text{fugacity}}{P}\n \n C_{v, dep} = T\\int_\\infty^V \\left(\\frac{\\partial^2 P}{\\partial \n T^2}\\right) dV = - T a \\left(\\sqrt{\\frac{1}{\\delta^{2} - 4 \n \\epsilon}} \\log{\\left (V - \\frac{\\delta^{2}}{2} \\sqrt{\\frac{1}{\n \\delta^{2} - 4 \\epsilon}} + \\frac{\\delta}{2} + 2 \\epsilon \\sqrt{\n \\frac{1}{\\delta^{2} - 4 \\epsilon}} \\right )} - \\sqrt{\\frac{1}{\n \\delta^{2} - 4 \\epsilon}} \\log{\\left (V + \\frac{\\delta^{2}}{2} \n \\sqrt{\\frac{1}{\\delta^{2} - 4 \\epsilon}} + \\frac{\\delta}{2} \n - 2 \\epsilon \\sqrt{\\frac{1}{\\delta^{2} - 4 \\epsilon}} \\right )}\n \\right) \\frac{d^{2} \\alpha{\\left (T \\right )} }{d T^{2}} \n \n C_{p, dep} = (C_p-C_v)_{\\text{from EOS}} + C_{v, dep} - R\n \n \n References\n ----------\n .. [1] Thorade, Matthis, and Ali Saadat. \"Partial Derivatives of \n Thermodynamic State Properties for Dynamic Simulation.\" \n Environmental Earth Sciences 70, no. 8 (April 10, 2013): 3497-3503.\n doi:10.1007/s12665-013-2394-z.\n .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th \n edition. New York: McGraw-Hill Professional, 2000.\n .. [3] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n Butterworth-Heinemann, 1985.\n '''\n ([dP_dT, dP_dV, dV_dT, dV_dP, dT_dV, dT_dP], \n [d2P_dT2, d2P_dV2, d2V_dT2, d2V_dP2, d2T_dV2, d2T_dP2],\n [d2V_dPdT, d2P_dTdV, d2T_dPdV],\n [H_dep, S_dep, Cv_dep]) = self.derivatives_and_departures(T, P, V, b, delta, epsilon, a_alpha, da_alpha_dT, d2a_alpha_dT2, quick=quick)\n \n beta = dV_dT/V # isobaric_expansion(V, dV_dT)\n kappa = -dV_dP/V # isothermal_compressibility(V, dV_dP)\n Cp_m_Cv = -T*dP_dT*dP_dT/dP_dV # Cp_minus_Cv(T, dP_dT, dP_dV)\n \n Cp_dep = Cp_m_Cv + Cv_dep - R\n \n V_dep = (V - R*T/P) \n U_dep = H_dep - P*V_dep\n G_dep = H_dep - T*S_dep\n A_dep = U_dep - T*S_dep\n fugacity = P*exp(G_dep/(R*T))\n phi = fugacity/P\n \n PIP = V*(d2P_dTdV/dP_dT - d2P_dV2/dP_dV) # phase_identification_parameter(V, dP_dT, dP_dV, d2P_dV2, d2P_dTdV)\n phase = 'l' if PIP > 1 else 'g' # phase_identification_parameter_phase(PIP)\n \n if phase == 'l':\n self.Z_l = self.P*V/(R*self.T)\n self.beta_l, self.kappa_l = beta, kappa\n self.PIP_l, self.Cp_minus_Cv_l = PIP, Cp_m_Cv\n \n self.dP_dT_l, self.dP_dV_l, self.dV_dT_l = dP_dT, dP_dV, dV_dT\n self.dV_dP_l, self.dT_dV_l, self.dT_dP_l = dV_dP, dT_dV, dT_dP\n \n self.d2P_dT2_l, self.d2P_dV2_l = d2P_dT2, d2P_dV2\n self.d2V_dT2_l, self.d2V_dP2_l = d2V_dT2, d2V_dP2\n self.d2T_dV2_l, self.d2T_dP2_l = d2T_dV2, d2T_dP2\n \n self.d2V_dPdT_l, self.d2P_dTdV_l, self.d2T_dPdV_l = d2V_dPdT, d2P_dTdV, d2T_dPdV\n \n self.H_dep_l, self.S_dep_l, self.V_dep_l = H_dep, S_dep, V_dep, \n self.U_dep_l, self.G_dep_l, self.A_dep_l = U_dep, G_dep, A_dep, \n self.fugacity_l, self.phi_l = fugacity, phi\n self.Cp_dep_l, self.Cv_dep_l = Cp_dep, Cv_dep\n else:\n self.Z_g = self.P*V/(R*self.T)\n self.beta_g, self.kappa_g = beta, kappa\n self.PIP_g, self.Cp_minus_Cv_g = PIP, Cp_m_Cv\n \n self.dP_dT_g, self.dP_dV_g, self.dV_dT_g = dP_dT, dP_dV, dV_dT\n self.dV_dP_g, self.dT_dV_g, self.dT_dP_g = dV_dP, dT_dV, dT_dP\n \n self.d2P_dT2_g, self.d2P_dV2_g = d2P_dT2, d2P_dV2\n self.d2V_dT2_g, self.d2V_dP2_g = d2V_dT2, d2V_dP2\n self.d2T_dV2_g, self.d2T_dP2_g = d2T_dV2, d2T_dP2\n \n self.d2V_dPdT_g, self.d2P_dTdV_g, self.d2T_dPdV_g = d2V_dPdT, d2P_dTdV, d2T_dPdV\n \n self.H_dep_g, self.S_dep_g, self.V_dep_g = H_dep, S_dep, V_dep, \n self.U_dep_g, self.G_dep_g, self.A_dep_g = U_dep, G_dep, A_dep, \n self.fugacity_g, self.phi_g = fugacity, phi\n self.Cp_dep_g, self.Cv_dep_g = Cp_dep, Cv_dep\n return phase", "response": "r Sets all interesting properties of a single entry in the system from the solution."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef dPsat_dT(self, T):\n r'''Generic method to calculate the temperature derivative of vapor \n pressure for a specified `T`. Implements the analytical derivative\n of the two polynomials described in `Psat`.\n \n As with `Psat`, results above the critical temperature are meaningless. \n The first-order polynomial which is used to calculate it under 0.32 Tc\n may not be physicall meaningful, due to there normally not being a \n volume solution to the EOS which can produce that low of a pressure.\n \n Parameters\n ----------\n T : float\n Temperature, [K]\n\n Returns\n -------\n dPsat_dT : float\n Derivative of vapor pressure with respect to temperature, [Pa/K]\n \n Notes\n -----\n There is a small step change at 0.32 Tc for all EOS due to the two\n switch between polynomials at that point.\n \n Useful for calculating enthalpy of vaporization with the Clausius\n Clapeyron Equation. Derived with SymPy's diff and cse.\n '''\n a_alphas = self.a_alpha_and_derivatives(T)\n alpha, d_alpha_dT = a_alphas[0]/self.a, a_alphas[1]/self.a\n Tr = T/self.Tc\n if Tr >= 0.32:\n c = self.Psat_coeffs\n x0 = alpha/T\n x1 = -self.Tc*x0 + 1\n x2 = c[0]*x1\n x3 = c[2] - x1*(c[1] - x2)\n x4 = c[3] - x1*x3\n x5 = c[4] - x1*x4\n x6 = c[5] - x1*x5\n x7 = c[6] - x1*x6\n x8 = c[7] - x1*x7\n x9 = c[8] - x1*x8\n return self.Pc*(-(d_alpha_dT - x0)*(-c[9] + x1*x9 + x1*(-x1*(-x1*(-x1*(-x1*(-x1*(-x1*(-x1*(c[1] - 2*x2) + x3) + x4) + x5) + x6) + x7) + x8) + x9)) + 1./self.Tc)*exp(c[10] - x1*(c[9] - x1*(c[8] - x1*(c[7] - x1*(c[6] - x1*(c[5] - x1*(c[4] - x1*(c[3] - x1*(c[2] + x1*(-c[1] + x2)))))))))) \n else:\n c = self.Psat_coeffs_limiting\n return self.Pc*T*c[0]*(self.Tc*d_alpha_dT/T - self.Tc*alpha/(T*T))*exp(c[0]*(-1. + self.Tc*alpha/T) + c[1])/self.Tc + self.Pc*exp(c[0]*(-1. + self.Tc*alpha/T) + c[1])/self.Tc", "response": "Generic method to calculate the temperature derivative of vapor edition for a specified temperature."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef V_g_sat(self, T):\n r'''Method to calculate molar volume of the vapor phase along the\n saturation line.\n \n Parameters\n ----------\n T : float\n Temperature, [K]\n\n Returns\n -------\n V_g_sat : float\n Gas molar volume along the saturation line, [m^3/mol]\n \n Notes\n -----\n Computers `Psat`, and then uses `volume_solutions` to obtain the three\n possible molar volumes. The highest value is returned.\n '''\n Psat = self.Psat(T)\n a_alpha = self.a_alpha_and_derivatives(T, full=False)\n Vs = self.volume_solutions(T, Psat, self.b, self.delta, self.epsilon, a_alpha)\n # Assume we can safely take the Vmax as gas, Vmin as l on the saturation line\n return max([i.real for i in Vs])", "response": "r Method to calculate the gas molar volume of the vapor phase along the saturation line."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Heyen(self, T, full=True, quick=True):\n r'''Method to calculate `a_alpha` and its first and second\n derivatives according to Heyen (1980) [1]_. Returns `a_alpha`, `da_alpha_dT`, \n and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n documentation. Two coefficients needed.\n \n .. math::\n \\alpha = e^{c_{1} \\left(- \\left(\\frac{T}{Tc}\\right)^{c_{2}}\n + 1\\right)}\n\n References\n ----------\n .. [1] Heyen, G. Liquid and Vapor Properties from a Cubic Equation of \n State. In \"Proceedings of the 2nd International Conference on Phase \n Equilibria and Fluid Properties in the Chemical Industry\". DECHEMA: \n Frankfurt, 1980; p 9-13.\n '''\n c1, c2 = self.alpha_function_coeffs\n T, Tc, a = self.T, self.Tc, self.a\n a_alpha = a*exp(c1*(1 -(T/Tc)**c2))\n if not full:\n return a_alpha\n else:\n da_alpha_dT = -a*c1*c2*(T/Tc)**c2*exp(c1*(-(T/Tc)**c2 + 1))/T\n d2a_alpha_dT2 = a*c1*c2*(T/Tc)**c2*(c1*c2*(T/Tc)**c2 - c2 + 1)*exp(-c1*((T/Tc)**c2 - 1))/T**2\n return a_alpha, da_alpha_dT, d2a_alpha_dT2", "response": "Method to calculate a_alpha da_alpha_dT d2a_alpha_dT2 based on Heyen method."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef Yu_Lu(self, T, full=True, quick=True):\n r'''Method to calculate `a_alpha` and its first and second\n derivatives according to Yu and Lu (1987) [1]_. Returns `a_alpha`, \n `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` \n for more documentation. Four coefficients needed.\n \n .. math::\n \\alpha = 10^{c_{4} \\left(- \\frac{T}{Tc} + 1\\right) \\left(\n \\frac{T^{2} c_{3}}{Tc^{2}} + \\frac{T c_{2}}{Tc} + c_{1}\\right)}\n\n References\n ----------\n .. [1] Yu, Jin-Min, and Benjamin C. -Y. Lu. \"A Three-Parameter Cubic \n Equation of State for Asymmetric Mixture Density Calculations.\" \n Fluid Phase Equilibria 34, no. 1 (January 1, 1987): 1-19. \n doi:10.1016/0378-3812(87)85047-1. \n '''\n c1, c2, c3, c4 = self.alpha_function_coeffs\n T, Tc, a = self.T, self.Tc, self.a\n a_alpha = a*10**(c4*(-T/Tc + 1)*(T**2*c3/Tc**2 + T*c2/Tc + c1))\n if not full:\n return a_alpha\n else:\n da_alpha_dT = a*(10**(c4*(-T/Tc + 1)*(T**2*c3/Tc**2 + T*c2/Tc + c1))*(c4*(-T/Tc + 1)*(2*T*c3/Tc**2 + c2/Tc) - c4*(T**2*c3/Tc**2 + T*c2/Tc + c1)/Tc)*log(10))\n d2a_alpha_dT2 = a*(10**(-c4*(T/Tc - 1)*(T**2*c3/Tc**2 + T*c2/Tc + c1))*c4*(-4*T*c3/Tc - 2*c2 - 2*c3*(T/Tc - 1) + c4*(T**2*c3/Tc**2 + T*c2/Tc + c1 + (T/Tc - 1)*(2*T*c3/Tc + c2))**2*log(10))*log(10)/Tc**2)\n return a_alpha, da_alpha_dT, d2a_alpha_dT2", "response": "Method to calculate a_alpha da_alpha_dT and d2a_alpha_dT2 according to Yu and Lu."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef Trebble_Bishnoi(self, T, full=True, quick=True):\n r'''Method to calculate `a_alpha` and its first and second\n derivatives according to Trebble and Bishnoi (1987) [1]_. Returns `a_alpha`, \n `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` \n for more documentation. One coefficient needed.\n \n .. math::\n \\alpha = e^{c_{1} \\left(- \\frac{T}{Tc} + 1\\right)}\n\n References\n ----------\n .. [1] Trebble, M. A., and P. R. Bishnoi. \"Development of a New Four-\n Parameter Cubic Equation of State.\" Fluid Phase Equilibria 35, no. 1\n (September 1, 1987): 1-18. doi:10.1016/0378-3812(87)80001-8.\n '''\n c1 = self.alpha_function_coeffs\n T, Tc, a = self.T, self.Tc, self.a\n a_alpha = a*exp(c1*(-T/Tc + 1))\n if not full:\n return a_alpha\n else:\n da_alpha_dT = a*-c1*exp(c1*(-T/Tc + 1))/Tc\n d2a_alpha_dT2 = a*c1**2*exp(-c1*(T/Tc - 1))/Tc**2\n return a_alpha, da_alpha_dT, d2a_alpha_dT2", "response": "Method to calculate a_alpha da_alpha_dT and d2a_alpha_dT2 according to Trebble and Bishnoi."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef Almeida(self, T, full=True, quick=True):\n r'''Method to calculate `a_alpha` and its first and second\n derivatives according to Almeida et al. (1991) [1]_. Returns `a_alpha`, \n `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` \n for more documentation. Three coefficients needed.\n \n .. math::\n \\alpha = e^{c_{1} \\left(- \\frac{T}{Tc} + 1\\right) \\left|{\n \\frac{T}{Tc} - 1}\\right|^{c_{2} - 1} + c_{3} \\left(-1 \n + \\frac{Tc}{T}\\right)}\n\n References\n ----------\n .. [1] Almeida, G. S., M. Aznar, and A. S. Telles. \"Uma Nova Forma de \n Depend\u00eancia Com a Temperatura Do Termo Atrativo de Equa\u00e7\u00f5es de \n Estado C\u00fabicas.\" RBE, Rev. Bras. Eng., Cad. Eng. Quim 8 (1991): 95.\n '''\n # Note: For the second derivative, requires the use a CAS which can \n # handle the assumption that Tr-1 != 0.\n c1, c2, c3 = self.alpha_function_coeffs\n T, Tc, a = self.T, self.Tc, self.a\n a_alpha = a*exp(c1*(-T/Tc + 1)*abs(T/Tc - 1)**(c2 - 1) + c3*(-1 + Tc/T))\n if not full:\n return a_alpha\n else:\n da_alpha_dT = a*((c1*(c2 - 1)*(-T/Tc + 1)*abs(T/Tc - 1)**(c2 - 1)*copysign(1, T/Tc - 1)/(Tc*Abs(T/Tc - 1)) - c1*abs(T/Tc - 1)**(c2 - 1)/Tc - Tc*c3/T**2)*exp(c1*(-T/Tc + 1)*abs(T/Tc - 1)**(c2 - 1) + c3*(-1 + Tc/T)))\n d2a_alpha_dT2 = a*exp(c3*(Tc/T - 1) - c1*abs(T/Tc - 1)**(c2 - 1)*(T/Tc - 1))*((c1*abs(T/Tc - 1)**(c2 - 1))/Tc + (Tc*c3)/T**2 + (c1*abs(T/Tc - 1)**(c2 - 2)*copysign(1, T/Tc - 1)*(c2 - 1)*(T/Tc - 1))/Tc)**2 - exp(c3*(Tc/T - 1) - c1*abs(T/Tc - 1)**(c2 - 1)*(T/Tc - 1))*((2*c1*abs(T/Tc - 1)**(c2 - 2)*copysign(1, T/Tc - 1)*(c2 - 1))/Tc**2 - (2*Tc*c3)/T**3 + (c1*abs(T/Tc - 1)**(c2 - 3)*copysign(1, T/Tc - 1)**2*(c2 - 1)*(c2 - 2)*(T/Tc - 1))/Tc**2)\n return a_alpha, da_alpha_dT, d2a_alpha_dT2", "response": "Method to calculate a_alpha da_alpha_dT and d2a_alpha_dT2 according to Almeida et al."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef a_alpha_and_derivatives(self, T, full=True, quick=True):\n r'''Method to calculate `a_alpha` and its first and second\n derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n documentation. Uses the set values of `Tc`, `kappa`, and `a`. \n \n For use in `solve_T`, returns only `a_alpha` if full is False.\n\n .. math::\n a\\alpha = a \\left(\\kappa \\left(- \\frac{T^{0.5}}{Tc^{0.5}} \n + 1\\right) + 1\\right)^{2}\n \n \\frac{d a\\alpha}{dT} = - \\frac{1.0 a \\kappa}{T^{0.5} Tc^{0.5}}\n \\left(\\kappa \\left(- \\frac{T^{0.5}}{Tc^{0.5}} + 1\\right) + 1\\right)\n\n \\frac{d^2 a\\alpha}{dT^2} = 0.5 a \\kappa \\left(- \\frac{1}{T^{1.5} \n Tc^{0.5}} \\left(\\kappa \\left(\\frac{T^{0.5}}{Tc^{0.5}} - 1\\right)\n - 1\\right) + \\frac{\\kappa}{T^{1.0} Tc^{1.0}}\\right)\n '''\n if not full:\n return self.a*(1 + self.kappa*(1-(T/self.Tc)**0.5))**2\n else:\n if quick:\n Tc, kappa = self.Tc, self.kappa\n x0 = T**0.5\n x1 = Tc**-0.5\n x2 = kappa*(x0*x1 - 1.) - 1.\n x3 = self.a*kappa\n \n a_alpha = self.a*x2*x2\n da_alpha_dT = x1*x2*x3/x0\n d2a_alpha_dT2 = x3*(-0.5*T**-1.5*x1*x2 + 0.5/(T*Tc)*kappa)\n else:\n a_alpha = self.a*(1 + self.kappa*(1-(T/self.Tc)**0.5))**2\n da_alpha_dT = -self.a*self.kappa*sqrt(T/self.Tc)*(self.kappa*(-sqrt(T/self.Tc) + 1.) + 1.)/T\n d2a_alpha_dT2 = self.a*self.kappa*(self.kappa/self.Tc - sqrt(T/self.Tc)*(self.kappa*(sqrt(T/self.Tc) - 1.) - 1.)/T)/(2.*T)\n return a_alpha, da_alpha_dT, d2a_alpha_dT2", "response": "Method to calculate a_alpha and a_alpha_dT for a given T."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef solve_T(self, P, V, quick=True):\n r'''Method to calculate `T` from a specified `P` and `V` for the PRSV\n EOS. Uses `Tc`, `a`, `b`, `kappa0` and `kappa` as well, obtained from \n the class's namespace.\n\n Parameters\n ----------\n P : float\n Pressure, [Pa]\n V : float\n Molar volume, [m^3/mol]\n quick : bool, optional\n Whether to use a SymPy cse-derived expression (somewhat faster) or \n individual formulas.\n\n Returns\n -------\n T : float\n Temperature, [K]\n \n Notes\n -----\n Not guaranteed to produce a solution. There are actually two solution,\n one much higher than normally desired; it is possible the solver could\n converge on this. \n '''\n Tc, a, b, kappa0, kappa1 = self.Tc, self.a, self.b, self.kappa0, self.kappa1\n if quick:\n x0 = V - b\n R_x0 = R/x0\n x3 = (100.*(V*(V + b) + b*x0))\n x4 = 10.*kappa0\n kappa110 = kappa1*10.\n kappa17 = kappa1*7.\n def to_solve(T):\n x1 = T/Tc\n x2 = x1**0.5\n return (T*R_x0 - a*((x4 - (kappa110*x1 - kappa17)*(x2 + 1.))*(x2 - 1.) - 10.)**2/x3) - P\n else:\n def to_solve(T):\n P_calc = R*T/(V - b) - a*((kappa0 + kappa1*(sqrt(T/Tc) + 1)*(-T/Tc + 7/10))*(-sqrt(T/Tc) + 1) + 1)**2/(V*(V + b) + b*(V - b))\n return P_calc - P\n return newton(to_solve, Tc*0.5)", "response": "r Method to calculate T from a specified P and V."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef a_alpha_and_derivatives(self, T, full=True, quick=True):\n r'''Method to calculate `a_alpha` and its first and second\n derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n documentation. Uses the set values of `Tc`, `kappa0`, `kappa1`, and \n `a`. \n \n For use in root-finding, returns only `a_alpha` if full is False.\n\n The `a_alpha` function is shown below; its first and second derivatives\n are long available through the SymPy expression under it.\n\n .. math::\n a\\alpha = a \\left(\\left(\\kappa_{0} + \\kappa_{1} \\left(\\sqrt{\\frac{\n T}{Tc}} + 1\\right) \\left(- \\frac{T}{Tc} + \\frac{7}{10}\\right)\n \\right) \\left(- \\sqrt{\\frac{T}{Tc}} + 1\\right) + 1\\right)^{2}\n \n >>> from sympy import *\n >>> P, T, V = symbols('P, T, V')\n >>> Tc, Pc, omega = symbols('Tc, Pc, omega')\n >>> R, a, b, kappa0, kappa1 = symbols('R, a, b, kappa0, kappa1')\n >>> kappa = kappa0 + kappa1*(1 + sqrt(T/Tc))*(Rational(7, 10)-T/Tc)\n >>> a_alpha = a*(1 + kappa*(1-sqrt(T/Tc)))**2\n >>> # diff(a_alpha, T)\n >>> # diff(a_alpha, T, 2)\n '''\n Tc, a, kappa0, kappa1 = self.Tc, self.a, self.kappa0, self.kappa1\n if not full:\n return a*((kappa0 + kappa1*(sqrt(T/Tc) + 1)*(-T/Tc + 0.7))*(-sqrt(T/Tc) + 1) + 1)**2\n else:\n if quick:\n x1 = T/Tc\n x2 = x1**0.5\n x3 = x2 - 1.\n x4 = 10.*x1 - 7.\n x5 = x2 + 1.\n x6 = 10.*kappa0 - kappa1*x4*x5\n x7 = x3*x6\n x8 = x7*0.1 - 1.\n x10 = x6/T\n x11 = kappa1*x3\n x12 = x4/T\n x13 = 20./Tc*x5 + x12*x2\n x14 = -x10*x2 + x11*x13\n a_alpha = a*x8*x8\n da_alpha_dT = -a*x14*x8*0.1\n d2a_alpha_dT2 = a*(x14*x14 - x2/T*(x7 - 10.)*(2.*kappa1*x13 + x10 + x11*(40./Tc - x12)))/200.\n else:\n a_alpha = a*((kappa0 + kappa1*(sqrt(T/Tc) + 1)*(-T/Tc + 0.7))*(-sqrt(T/Tc) + 1) + 1)**2\n da_alpha_dT = a*((kappa0 + kappa1*(sqrt(T/Tc) + 1)*(-T/Tc + 0.7))*(-sqrt(T/Tc) + 1) + 1)*(2*(-sqrt(T/Tc) + 1)*(-kappa1*(sqrt(T/Tc) + 1)/Tc + kappa1*sqrt(T/Tc)*(-T/Tc + 0.7)/(2*T)) - sqrt(T/Tc)*(kappa0 + kappa1*(sqrt(T/Tc) + 1)*(-T/Tc + 0.7))/T)\n d2a_alpha_dT2 = a*((kappa1*(sqrt(T/Tc) - 1)*(20*(sqrt(T/Tc) + 1)/Tc + sqrt(T/Tc)*(10*T/Tc - 7)/T) - sqrt(T/Tc)*(10*kappa0 - kappa1*(sqrt(T/Tc) + 1)*(10*T/Tc - 7))/T)**2 - sqrt(T/Tc)*((10*kappa0 - kappa1*(sqrt(T/Tc) + 1)*(10*T/Tc - 7))*(sqrt(T/Tc) - 1) - 10)*(kappa1*(40/Tc - (10*T/Tc - 7)/T)*(sqrt(T/Tc) - 1) + 2*kappa1*(20*(sqrt(T/Tc) + 1)/Tc + sqrt(T/Tc)*(10*T/Tc - 7)/T) + (10*kappa0 - kappa1*(sqrt(T/Tc) + 1)*(10*T/Tc - 7))/T)/T)/200\n return a_alpha, da_alpha_dT, d2a_alpha_dT2", "response": "r Method to calculate a_alpha and a_alpha_dT for a specific set of entry points."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef a_alpha_and_derivatives(self, T, full=True, quick=True):\n r'''Method to calculate `a_alpha` and its first and second\n derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n documentation. Uses the set values of `a`.\n \n .. math::\n a\\alpha = a\n \n \\frac{d a\\alpha}{dT} = 0\n\n \\frac{d^2 a\\alpha}{dT^2} = 0\n '''\n if not full:\n return self.a\n else:\n a_alpha = self.a\n da_alpha_dT = 0.0\n d2a_alpha_dT2 = 0.0\n return a_alpha, da_alpha_dT, d2a_alpha_dT2", "response": "r Method to calculate a_alpha da_alpha_dT and d2a_alpha_dT2 for this EOS."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef main_derivatives_and_departures(T, P, V, b, delta, epsilon, a_alpha,\n da_alpha_dT, d2a_alpha_dT2, quick=True):\n '''Re-implementation of derivatives and excess property calculations, \n as ZeroDivisionError errors occur with the general solution. The \n following derivation is the source of these formulas.\n \n >>> from sympy import *\n >>> P, T, V, R, b, a = symbols('P, T, V, R, b, a')\n >>> P_vdw = R*T/(V-b) - a/(V*V)\n >>> vdw = P_vdw - P\n >>> \n >>> dP_dT = diff(vdw, T)\n >>> dP_dV = diff(vdw, V)\n >>> d2P_dT2 = diff(vdw, T, 2)\n >>> d2P_dV2 = diff(vdw, V, 2)\n >>> d2P_dTdV = diff(vdw, T, V)\n >>> H_dep = integrate(T*dP_dT - P_vdw, (V, oo, V))\n >>> H_dep += P*V - R*T\n >>> S_dep = integrate(dP_dT - R/V, (V,oo,V))\n >>> S_dep += R*log(P*V/(R*T))\n >>> Cv_dep = T*integrate(d2P_dT2, (V,oo,V))\n >>> \n >>> dP_dT, dP_dV, d2P_dT2, d2P_dV2, d2P_dTdV, H_dep, S_dep, Cv_dep\n (R/(V - b), -R*T/(V - b)**2 + 2*a/V**3, 0, 2*(R*T/(V - b)**3 - 3*a/V**4), -R/(V - b)**2, P*V - R*T - a/V, R*(-log(V) + log(V - b)) + R*log(P*V/(R*T)), 0)\n '''\n dP_dT = R/(V - b)\n dP_dV = -R*T/(V - b)**2 + 2*a_alpha/V**3\n d2P_dT2 = 0\n d2P_dV2 = 2*(R*T/(V - b)**3 - 3*a_alpha/V**4)\n d2P_dTdV = -R/(V - b)**2\n H_dep = P*V - R*T - a_alpha/V\n S_dep = R*(-log(V) + log(V - b)) + R*log(P*V/(R*T))\n Cv_dep = 0\n return [dP_dT, dP_dV, d2P_dT2, d2P_dV2, d2P_dTdV, H_dep, S_dep, Cv_dep]", "response": "Re - implementation of derivatives and excess property calculations and ZeroDivisionError errors occur with the general solution."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef a_alpha_and_derivatives(self, T, full=True, quick=True):\n r'''Method to calculate `a_alpha` and its first and second\n derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and \n `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more \n documentation. Uses the set values of `Tc`, `m`, and `a`.\n \n .. math::\n a\\alpha = a \\left(m \\left(- \\sqrt{\\frac{T}{Tc}} + 1\\right)\n + 1\\right)^{2}\n \n \\frac{d a\\alpha}{dT} = \\frac{a m}{T} \\sqrt{\\frac{T}{Tc}} \\left(m\n \\left(\\sqrt{\\frac{T}{Tc}} - 1\\right) - 1\\right)\n\n \\frac{d^2 a\\alpha}{dT^2} = \\frac{a m \\sqrt{\\frac{T}{Tc}}}{2 T^{2}}\n \\left(m + 1\\right)\n '''\n a, Tc, m = self.a, self.Tc, self.m\n sqTr = (T/Tc)**0.5\n a_alpha = a*(m*(1. - sqTr) + 1.)**2\n if not full:\n return a_alpha\n else:\n da_alpha_dT = -a*m*sqTr*(m*(-sqTr + 1.) + 1.)/T\n d2a_alpha_dT2 = a*m*sqTr*(m + 1.)/(2.*T*T)\n return a_alpha, da_alpha_dT, d2a_alpha_dT2", "response": "Method to calculate a_alpha da_alpha_dT and d2a_alpha_dT2 for this EOS."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Tb(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[PSAT_DEFINITION]):\n r'''This function handles the retrieval of a chemical's boiling\n point. Lookup is based on CASRNs. Will automatically select a data\n source to use if no Method is provided; returns None if the data is not\n available.\n\n Prefered sources are 'CRC Physical Constants, organic' for organic\n chemicals, and 'CRC Physical Constants, inorganic' for inorganic\n chemicals. Function has data for approximately 13000 chemicals.\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n Tb : float\n Boiling temperature, [K]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain Tb with the given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n A string for the method name to use, as defined by constants in\n Tb_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n Tb for the desired chemical, and will return methods instead of Tb\n IgnoreMethods : list, optional\n A list of methods to ignore in obtaining the full list of methods,\n useful for for performance reasons and ignoring inaccurate methods\n\n Notes\n -----\n A total of four methods are available for this function. They are:\n\n * 'CRC_ORG', a compillation of data on organics\n as published in [1]_.\n * 'CRC_INORG', a compillation of data on\n inorganic as published in [1]_.\n * 'YAWS', a large compillation of data from a\n variety of sources; no data points are sourced in the work of [2]_.\n * 'PSAT_DEFINITION', calculation of boiling point from a\n vapor pressure calculation. This is normally off by a fraction of a\n degree even in the best cases. Listed in IgnoreMethods by default\n for performance reasons.\n\n Examples\n --------\n >>> Tb('7732-18-5')\n 373.124\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n .. [2] Yaws, Carl L. Thermophysical Properties of Chemicals and\n Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n Publishing, 2014.\n '''\n def list_methods():\n methods = []\n if CASRN in CRC_inorganic_data.index and not np.isnan(CRC_inorganic_data.at[CASRN, 'Tb']):\n methods.append(CRC_INORG)\n if CASRN in CRC_organic_data.index and not np.isnan(CRC_organic_data.at[CASRN, 'Tb']):\n methods.append(CRC_ORG)\n if CASRN in Yaws_data.index:\n methods.append(YAWS)\n if PSAT_DEFINITION not in IgnoreMethods:\n try:\n # For some chemicals, vapor pressure range will exclude Tb\n VaporPressure(CASRN=CASRN).solve_prop(101325.)\n methods.append(PSAT_DEFINITION)\n except: # pragma: no cover\n pass\n if IgnoreMethods:\n for Method in IgnoreMethods:\n if Method in methods:\n methods.remove(Method)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == CRC_INORG:\n return float(CRC_inorganic_data.at[CASRN, 'Tb'])\n elif Method == CRC_ORG:\n return float(CRC_organic_data.at[CASRN, 'Tb'])\n elif Method == YAWS:\n return float(Yaws_data.at[CASRN, 'Tb'])\n elif Method == PSAT_DEFINITION:\n return VaporPressure(CASRN=CASRN).solve_prop(101325.)\n elif Method == NONE:\n return None\n else:\n raise Exception('Failure in in function')", "response": "r Returns a new object with the boiling temperature for the given CASRN and methods."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Clapeyron(T, Tc, Pc, dZ=1, Psat=101325):\n r'''Calculates enthalpy of vaporization at arbitrary temperatures using the\n Clapeyron equation.\n\n The enthalpy of vaporization is given by:\n\n .. math::\n \\Delta H_{vap} = RT \\Delta Z \\frac{\\ln (P_c/Psat)}{(1-T_{r})}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n dZ : float\n Change in compressibility factor between liquid and gas, []\n Psat : float\n Saturation pressure of fluid [Pa], optional\n\n Returns\n -------\n Hvap : float\n Enthalpy of vaporization, [J/mol]\n\n Notes\n -----\n No original source is available for this equation.\n [1]_ claims this equation overpredicts enthalpy by several percent.\n Under Tr = 0.8, dZ = 1 is a reasonable assumption.\n This equation is most accurate at the normal boiling point.\n\n Internal units are bar.\n\n WARNING: I believe it possible that the adjustment for pressure may be incorrect\n\n Examples\n --------\n Problem from Perry's examples.\n\n >>> Clapeyron(T=294.0, Tc=466.0, Pc=5.55E6)\n 26512.354585061985\n\n References\n ----------\n .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n '''\n Tr = T/Tc\n return R*T*dZ*log(Pc/Psat)/(1. - Tr)", "response": "r Returns an enthalpy of vaporization at arbitrary temperatures using the Clapeyron equation."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef SMK(T, Tc, omega):\n r'''Calculates enthalpy of vaporization at arbitrary temperatures using a\n the work of [1]_; requires a chemical's critical temperature and\n acentric factor.\n\n The enthalpy of vaporization is given by:\n\n .. math::\n \\frac{\\Delta H_{vap}} {RT_c} =\n \\left( \\frac{\\Delta H_{vap}} {RT_c} \\right)^{(R1)} + \\left(\n \\frac{\\omega - \\omega^{(R1)}} {\\omega^{(R2)} - \\omega^{(R1)}} \\right)\n \\left[\\left( \\frac{\\Delta H_{vap}} {RT_c} \\right)^{(R2)} - \\left(\n \\frac{\\Delta H_{vap}} {RT_c} \\right)^{(R1)} \\right]\n\n \\left( \\frac{\\Delta H_{vap}} {RT_c} \\right)^{(R1)}\n = 6.537 \\tau^{1/3} - 2.467 \\tau^{5/6} - 77.251 \\tau^{1.208} +\n 59.634 \\tau + 36.009 \\tau^2 - 14.606 \\tau^3\n\n \\left( \\frac{\\Delta H_{vap}} {RT_c} \\right)^{(R2)} - \\left(\n \\frac{\\Delta H_{vap}} {RT_c} \\right)^{(R1)}=-0.133 \\tau^{1/3} - 28.215\n \\tau^{5/6} - 82.958 \\tau^{1.208} + 99.00 \\tau + 19.105 \\tau^2 -2.796 \\tau^3\n\n \\tau = 1-T/T_c\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n omega : float\n Acentric factor [-]\n\n Returns\n -------\n Hvap : float\n Enthalpy of vaporization, [J/mol]\n\n Notes\n -----\n The original article has been reviewed and found to have coefficients with\n slightly more precision. Additionally, the form of the equation is slightly\n different, but numerically equivalent.\n\n The refence fluids are:\n\n :math:`\\omega_0` = benzene = 0.212\n\n :math:`\\omega_1` = carbazole = 0.461\n\n A sample problem in the article has been verified. The numerical result\n presented by the author requires high numerical accuracy to obtain.\n\n Examples\n --------\n Problem in [1]_:\n\n >>> SMK(553.15, 751.35, 0.302)\n 39866.17647797959\n\n References\n ----------\n .. [1] Sivaraman, Alwarappa, Joe W. Magee, and Riki Kobayashi. \"Generalized\n Correlation of Latent Heats of Vaporization of Coal-Liquid Model Compounds\n between Their Freezing Points and Critical Points.\" Industrial &\n Engineering Chemistry Fundamentals 23, no. 1 (February 1, 1984): 97-100.\n doi:10.1021/i100013a017.\n '''\n omegaR1, omegaR2 = 0.212, 0.461\n A10 = 6.536924\n A20 = -2.466698\n A30 = -77.52141\n B10 = 59.63435\n B20 = 36.09887\n B30 = -14.60567\n\n A11 = -0.132584\n A21 = -28.21525\n A31 = -82.95820\n B11 = 99.00008\n B21 = 19.10458\n B31 = -2.795660\n\n tau = 1. - T/Tc\n L0 = A10*tau**(1/3.) + A20*tau**(5/6.) + A30*tau**(1-1/8. + 1/3.) + \\\n B10*tau + B20*tau**2 + B30*tau**3\n\n L1 = A11*tau**(1/3.) + A21*tau**(5/6.0) + A31*tau**(1-1/8. + 1/3.) + \\\n B11*tau + B21*tau**2 + B31*tau**3\n\n domega = (omega - omegaR1)/(omegaR2 - omegaR1)\n return R*Tc*(L0 + domega*L1)", "response": "r Returns a string that represents the smack of the chemical s critical temperature and acentric factor of the chemical s vaporization at arbitrary temperatures."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Velasco(T, Tc, omega):\n r'''Calculates enthalpy of vaporization at arbitrary temperatures using a\n the work of [1]_; requires a chemical's critical temperature and\n acentric factor.\n\n The enthalpy of vaporization is given by:\n\n .. math::\n \\Delta_{vap} H = RT_c(7.2729 + 10.4962\\omega + 0.6061\\omega^2)(1-T_r)^{0.38}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n omega : float\n Acentric factor [-]\n\n Returns\n -------\n Hvap : float\n Enthalpy of vaporization, [J/mol]\n\n Notes\n -----\n The original article has been reviewed. It is regressed from enthalpy of\n vaporization values at 0.7Tr, from 121 fluids in REFPROP 9.1.\n A value in the article was read to be similar, but slightly too low from\n that calculated here.\n\n Examples\n --------\n From graph, in [1]_ for perfluoro-n-heptane.\n\n >>> Velasco(333.2, 476.0, 0.5559)\n 33299.41734936356\n\n References\n ----------\n .. [1] Velasco, S., M. J. Santos, and J. A. White. \"Extended Corresponding\n States Expressions for the Changes in Enthalpy, Compressibility Factor\n and Constant-Volume Heat Capacity at Vaporization.\" The Journal of\n Chemical Thermodynamics 85 (June 2015): 68-76.\n doi:10.1016/j.jct.2015.01.011.\n '''\n return (7.2729 + 10.4962*omega + 0.6061*omega**2)*(1-T/Tc)**0.38*R*Tc", "response": "r Calculates the enthalpy of vaporization at arbitrary temperatures using a\n the work of the given chemical."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Riedel(Tb, Tc, Pc):\n r'''Calculates enthalpy of vaporization at the boiling point, using the\n Ridel [1]_ CSP method. Required information are critical temperature\n and pressure, and boiling point. Equation taken from [2]_ and [3]_.\n\n The enthalpy of vaporization is given by:\n\n .. math::\n \\Delta_{vap} H=1.093 T_b R\\frac{\\ln P_c-1.013}{0.930-T_{br}}\n\n Parameters\n ----------\n Tb : float\n Boiling temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n\n Returns\n -------\n Hvap : float\n Enthalpy of vaporization at the normal boiling point, [J/mol]\n\n Notes\n -----\n This equation has no example calculation in any source. The source has not\n been verified. It is equation 4-144 in Perry's. Perry's also claims that\n errors seldom surpass 5%.\n\n [2]_ is the source of example work here, showing a calculation at 0.0%\n error.\n\n Internal units of pressure are bar.\n\n Examples\n --------\n Pyridine, 0.0% err vs. exp: 35090 J/mol; from Poling [2]_.\n\n >>> Riedel(388.4, 620.0, 56.3E5)\n 35089.78989646058\n\n References\n ----------\n .. [1] Riedel, L. \"Eine Neue Universelle Dampfdruckformel Untersuchungen\n Uber Eine Erweiterung Des Theorems Der Ubereinstimmenden Zustande. Teil\n I.\" Chemie Ingenieur Technik 26, no. 2 (February 1, 1954): 83-89.\n doi:10.1002/cite.330260206.\n .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n .. [3] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n '''\n Pc = Pc/1E5 # Pa to bar\n Tbr = Tb/Tc\n return 1.093*Tb*R*(log(Pc) - 1.013)/(0.93 - Tbr)", "response": "r References of the enthalpy of vaporization at the boiling point."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef Vetere(Tb, Tc, Pc, F=1):\n r'''Calculates enthalpy of vaporization at the boiling point, using the\n Vetere [1]_ CSP method. Required information are critical temperature\n and pressure, and boiling point. Equation taken from [2]_.\n\n The enthalpy of vaporization is given by:\n\n .. math::\n \\frac {\\Delta H_{vap}}{RT_b} = \\frac{\\tau_b^{0.38}\n \\left[ \\ln P_c - 0.513 + \\frac{0.5066}{P_cT_{br}^2}\\right]}\n {\\tau_b + F(1-\\tau_b^{0.38})\\ln T_{br}}\n\n Parameters\n ----------\n Tb : float\n Boiling temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n F : float, optional\n Constant for a fluid, [-]\n\n Returns\n -------\n Hvap : float\n Enthalpy of vaporization at the boiling point, [J/mol]\n\n Notes\n -----\n The equation cannot be found in the original source. It is believed that a\n second article is its source, or that DIPPR staff have altered the formulation.\n\n Internal units of pressure are bar.\n\n Examples\n --------\n Example as in [2]_, p2-487; exp: 25.73\n\n >>> Vetere(294.0, 466.0, 5.55E6)\n 26363.430021286465\n\n References\n ----------\n .. [1] Vetere, Alessandro. \"Methods to Predict the Vaporization Enthalpies\n at the Normal Boiling Temperature of Pure Compounds Revisited.\"\n Fluid Phase Equilibria 106, no. 1-2 (May 1, 1995): 1\u201310.\n doi:10.1016/0378-3812(94)02627-D.\n .. [2] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n '''\n Tbr = Tb/Tc\n taub = 1-Tb/Tc\n Pc = Pc/1E5\n term = taub**0.38*(log(Pc)-0.513 + 0.5066/Pc/Tbr**2) / (taub + F*(1-taub**0.38)*log(Tbr))\n return R*Tb*term", "response": "r Returns an enthalpy of vaporization at the boiling point."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ncalculates Watson vaporization of enthalpy for one temperature.", "response": "def Watson(T, Hvap_ref, T_Ref, Tc, exponent=0.38):\n '''\n Adjusts enthalpy of vaporization of enthalpy for another temperature, for one temperature.\n '''\n Tr = T/Tc\n Trefr = T_Ref/Tc\n H2 = Hvap_ref*((1-Tr)/(1-Trefr))**exponent\n return H2"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Hfus(T=298.15, P=101325, MW=None, AvailableMethods=False, Method=None, CASRN=''): # pragma: no cover\n '''This function handles the calculation of a chemical's enthalpy of fusion.\n Generally this, is used by the chemical class, as all parameters are passed.\n Calling the function directly works okay.\n\n Enthalpy of fusion is a weak function of pressure, and its effects are\n neglected.\n\n This API is considered experimental, and is expected to be removed in a\n future release in favor of a more complete object-oriented interface.\n\n '''\n def list_methods():\n methods = []\n if CASRN in CRCHfus_data.index:\n methods.append('CRC, at melting point')\n methods.append('None')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n if Method == 'CRC, at melting point':\n _Hfus = CRCHfus_data.at[CASRN, 'Hfus']\n elif Method == 'None' or not MW:\n _Hfus = None\n else:\n raise Exception('Failure in in function')\n _Hfus = property_molar_to_mass(_Hfus, MW)\n return _Hfus", "response": "This function calculates the Hfus of a chemical s enthalpy of fusion."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef load_all_methods(self):\n r'''Method which picks out coefficients for the specified chemical\n from the various dictionaries and DataFrames storing it. All data is\n stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,\n and :obj:`all_methods` as a set of methods for which the data exists for.\n\n Called on initialization only. See the source code for the variables at\n which the coefficients are stored. The coefficients can safely be\n altered once the class is initialized. This method can be called again\n to reset the parameters.\n '''\n methods = []\n Tmins, Tmaxs = [], []\n if has_CoolProp and self.CASRN in coolprop_dict:\n methods.append(COOLPROP)\n self.CP_f = coolprop_fluids[self.CASRN]\n Tmins.append(self.CP_f.Tt); Tmaxs.append(self.CP_f.Tc)\n if self.CASRN in _VDISaturationDict:\n methods.append(VDI_TABULAR)\n Ts, props = VDI_tabular_data(self.CASRN, 'Hvap')\n self.VDI_Tmin = Ts[0]\n self.VDI_Tmax = Ts[-1]\n self.tabular_data[VDI_TABULAR] = (Ts, props)\n Tmins.append(self.VDI_Tmin); Tmaxs.append(self.VDI_Tmax)\n if self.CASRN in Alibakhshi_Cs.index and self.Tc:\n methods.append(ALIBAKHSHI)\n self.Alibakhshi_C = float(Alibakhshi_Cs.at[self.CASRN, 'C'])\n Tmaxs.append( max(self.Tc-100., 0) )\n if self.CASRN in CRCHvap_data.index and not np.isnan(CRCHvap_data.at[self.CASRN, 'HvapTb']):\n methods.append(CRC_HVAP_TB)\n self.CRC_HVAP_TB_Tb = float(CRCHvap_data.at[self.CASRN, 'Tb'])\n self.CRC_HVAP_TB_Hvap = float(CRCHvap_data.at[self.CASRN, 'HvapTb'])\n if self.CASRN in CRCHvap_data.index and not np.isnan(CRCHvap_data.at[self.CASRN, 'Hvap298']):\n methods.append(CRC_HVAP_298)\n self.CRC_HVAP_298 = float(CRCHvap_data.at[self.CASRN, 'Hvap298'])\n if self.CASRN in GharagheiziHvap_data.index:\n methods.append(GHARAGHEIZI_HVAP_298)\n self.GHARAGHEIZI_HVAP_298_Hvap = float(GharagheiziHvap_data.at[self.CASRN, 'Hvap298'])\n if all((self.Tc, self.omega)):\n methods.extend(self.CSP_methods)\n Tmaxs.append(self.Tc); Tmins.append(0)\n if all((self.Tc, self.Pc)):\n methods.append(CLAPEYRON)\n Tmaxs.append(self.Tc); Tmins.append(0)\n if all((self.Tb, self.Tc, self.Pc)):\n methods.extend(self.boiling_methods)\n Tmaxs.append(self.Tc); Tmins.append(0)\n if self.CASRN in Perrys2_150.index:\n methods.append(DIPPR_PERRY_8E)\n _, Tc, C1, C2, C3, C4, self.Perrys2_150_Tmin, self.Perrys2_150_Tmax = _Perrys2_150_values[Perrys2_150.index.get_loc(self.CASRN)].tolist()\n self.Perrys2_150_coeffs = [Tc, C1, C2, C3, C4]\n Tmins.append(self.Perrys2_150_Tmin); Tmaxs.append(self.Perrys2_150_Tmax)\n if self.CASRN in VDI_PPDS_4.index:\n _, MW, Tc, A, B, C, D, E = _VDI_PPDS_4_values[VDI_PPDS_4.index.get_loc(self.CASRN)].tolist()\n self.VDI_PPDS_coeffs = [A, B, C, D, E]\n self.VDI_PPDS_Tc = Tc\n self.VDI_PPDS_MW = MW\n methods.append(VDI_PPDS)\n Tmaxs.append(self.VDI_PPDS_Tc); \n self.all_methods = set(methods)\n if Tmins and Tmaxs:\n self.Tmin, self.Tmax = min(Tmins), max(Tmaxs)", "response": "r This method loads all methods for the specified chemicalical class and stores them as attributes."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef solubility_eutectic(T, Tm, Hm, Cpl=0, Cps=0, gamma=1):\n r'''Returns the maximum solubility of a solute in a solvent.\n\n .. math::\n \\ln x_i^L \\gamma_i^L = \\frac{\\Delta H_{m,i}}{RT}\\left(\n 1 - \\frac{T}{T_{m,i}}\\right) - \\frac{\\Delta C_{p,i}(T_{m,i}-T)}{RT}\n + \\frac{\\Delta C_{p,i}}{R}\\ln\\frac{T_m}{T}\n\n \\Delta C_{p,i} = C_{p,i}^L - C_{p,i}^S\n\n Parameters\n ----------\n T : float\n Temperature of the system [K]\n Tm : float\n Melting temperature of the solute [K]\n Hm : float\n Heat of melting at the melting temperature of the solute [J/mol]\n Cpl : float, optional\n Molar heat capacity of the solute as a liquid [J/mol/K]\n Cpls: float, optional\n Molar heat capacity of the solute as a solid [J/mol/K]\n gamma : float, optional\n Activity coefficient of the solute as a liquid [-]\n\n Returns\n -------\n x : float\n Mole fraction of solute at maximum solubility [-]\n\n Notes\n -----\n gamma is of the solute in liquid phase\n\n Examples\n --------\n From [1]_, matching example\n\n >>> solubility_eutectic(T=260., Tm=278.68, Hm=9952., Cpl=0, Cps=0, gamma=3.0176)\n 0.24340068761677464\n\n References\n ----------\n .. [1] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n Weinheim, Germany: Wiley-VCH, 2012.\n '''\n dCp = Cpl-Cps\n x = exp(- Hm/R/T*(1-T/Tm) + dCp*(Tm-T)/R/T - dCp/R*log(Tm/T))/gamma\n return x", "response": "r Returns the maximum solubility of a system in a liquid phase."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Tm_depression_eutectic(Tm, Hm, x=None, M=None, MW=None):\n r'''Returns the freezing point depression caused by a solute in a solvent.\n Can use either the mole fraction of the solute or its molality and the\n molecular weight of the solvent. Assumes ideal system behavior.\n\n .. math::\n \\Delta T_m = \\frac{R T_m^2 x}{\\Delta H_m}\n\n \\Delta T_m = \\frac{R T_m^2 (MW) M}{1000 \\Delta H_m}\n\n Parameters\n ----------\n Tm : float\n Melting temperature of the solute [K]\n Hm : float\n Heat of melting at the melting temperature of the solute [J/mol]\n x : float, optional\n Mole fraction of the solute [-]\n M : float, optional\n Molality [mol/kg]\n MW: float, optional\n Molecular weight of the solvent [g/mol]\n\n Returns\n -------\n dTm : float\n Freezing point depression [K]\n\n Notes\n -----\n MW is the molecular weight of the solvent. M is the molality of the solute.\n\n Examples\n --------\n From [1]_, matching example.\n\n >>> Tm_depression_eutectic(353.35, 19110, .02)\n 1.0864594900639515\n\n References\n ----------\n .. [1] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n Weinheim, Germany: Wiley-VCH, 2012.\n '''\n if x:\n dTm = R*Tm**2*x/Hm\n elif M and MW:\n MW = MW/1000. #g/mol to kg/mol\n dTm = R*Tm**2*MW*M/Hm\n else:\n raise Exception('Either molality or mole fraction of the solute must be specified; MW of the solvent is required also if molality is provided')\n return dTm", "response": "r Returns the freezing point depression caused by a solute in a solvent."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Yen_Woods_saturation(T, Tc, Vc, Zc):\n r'''Calculates saturation liquid volume, using the Yen and Woods [1]_ CSP\n method and a chemical's critical properties.\n\n The molar volume of a liquid is given by:\n\n .. math::\n Vc/Vs = 1 + A(1-T_r)^{1/3} + B(1-T_r)^{2/3} + D(1-T_r)^{4/3}\n\n D = 0.93-B\n\n A = 17.4425 - 214.578Z_c + 989.625Z_c^2 - 1522.06Z_c^3\n\n B = -3.28257 + 13.6377Z_c + 107.4844Z_c^2-384.211Z_c^3\n \\text{ if } Zc \\le 0.26\n\n B = 60.2091 - 402.063Z_c + 501.0 Z_c^2 + 641.0 Z_c^3\n \\text{ if } Zc \\ge 0.26\n\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Vc : float\n Critical volume of fluid [m^3/mol]\n Zc : float\n Critical compressibility of fluid, [-]\n\n Returns\n -------\n Vs : float\n Saturation liquid volume, [m^3/mol]\n\n Notes\n -----\n Original equation was in terms of density, but it is converted here.\n\n No example has been found, nor are there points in the article. However,\n it is believed correct. For compressed liquids with the Yen-Woods method,\n see the `YenWoods_compressed` function.\n\n Examples\n --------\n >>> Yen_Woods_saturation(300, 647.14, 55.45E-6, 0.245)\n 1.7695330765295693e-05\n\n References\n ----------\n .. [1] Yen, Lewis C., and S. S. Woods. \"A Generalized Equation for Computer\n Calculation of Liquid Densities.\" AIChE Journal 12, no. 1 (1966):\n 95-99. doi:10.1002/aic.690120119\n '''\n Tr = T/Tc\n A = 17.4425 - 214.578*Zc + 989.625*Zc**2 - 1522.06*Zc**3\n if Zc <= 0.26:\n B = -3.28257 + 13.6377*Zc + 107.4844*Zc**2 - 384.211*Zc**3\n else:\n B = 60.2091 - 402.063*Zc + 501.0*Zc**2 + 641.0*Zc**3\n D = 0.93 - B\n Vm = Vc/(1 + A*(1-Tr)**(1/3.) + B*(1-Tr)**(2/3.) + D*(1-Tr)**(4/3.))\n return Vm", "response": "r A function that calculates the saturation liquid volume using the Yen - Woods method."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef Yamada_Gunn(T, Tc, Pc, omega):\n r'''Calculates saturation liquid volume, using Yamada and Gunn CSP method\n and a chemical's critical properties and acentric factor.\n\n The molar volume of a liquid is given by:\n\n .. math::\n V_s = \\frac{RT_c}{P_c}{(0.29056-0.08775\\omega)}^{[1+(1-{T/T_c})^{2/7}]}\n\n Units are in m^3/mol.\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n omega : float\n Acentric factor for fluid, [-]\n\n Returns\n -------\n Vs : float\n saturation liquid volume, [m^3/mol]\n\n Notes\n -----\n This equation is an improvement on the Rackett equation.\n This is often presented as the Rackett equation.\n The acentric factor is used here, instead of the critical compressibility\n A variant using a reference fluid also exists\n\n Examples\n --------\n >>> Yamada_Gunn(300, 647.14, 22048320.0, 0.245)\n 2.1882836429895796e-05\n\n References\n ----------\n .. [1] Gunn, R. D., and Tomoyoshi Yamada. \"A Corresponding States\n Correlation of Saturated Liquid Volumes.\" AIChE Journal 17, no. 6\n (1971): 1341-45. doi:10.1002/aic.690170613\n .. [2] Yamada, Tomoyoshi, and Robert D. Gunn. \"Saturated Liquid Molar\n Volumes. Rackett Equation.\" Journal of Chemical & Engineering Data 18,\n no. 2 (1973): 234-36. doi:10.1021/je60057a006\n '''\n return R*Tc/Pc*(0.29056 - 0.08775*omega)**(1 + (1 - T/Tc)**(2/7.))", "response": "r Returns a base class for a given temperature Tc and pressure omega."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Townsend_Hales(T, Tc, Vc, omega):\n r'''Calculates saturation liquid density, using the Townsend and Hales\n CSP method as modified from the original Riedel equation. Uses\n chemical critical volume and temperature, as well as acentric factor\n\n The density of a liquid is given by:\n\n .. math::\n Vs = V_c/\\left(1+0.85(1-T_r)+(1.692+0.986\\omega)(1-T_r)^{1/3}\\right)\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Vc : float\n Critical volume of fluid [m^3/mol]\n omega : float\n Acentric factor for fluid, [-]\n\n Returns\n -------\n Vs : float\n Saturation liquid volume, [m^3/mol]\n\n Notes\n -----\n The requirement for critical volume and acentric factor requires all data.\n\n Examples\n --------\n >>> Townsend_Hales(300, 647.14, 55.95E-6, 0.3449)\n 1.8007361992619923e-05\n\n References\n ----------\n .. [1] Hales, J. L, and R Townsend. \"Liquid Densities from 293 to 490 K of\n Nine Aromatic Hydrocarbons.\" The Journal of Chemical Thermodynamics\n 4, no. 5 (1972): 763-72. doi:10.1016/0021-9614(72)90050-X\n '''\n Tr = T/Tc\n return Vc/(1 + 0.85*(1-Tr) + (1.692 + 0.986*omega)*(1-Tr)**(1/3.))", "response": "r Calculates the saturation liquid density using the Townsend and Hales ArcGIS method as modified from the original Riedel equation."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef Bhirud_normal(T, Tc, Pc, omega):\n r'''Calculates saturation liquid density using the Bhirud [1]_ CSP method.\n Uses Critical temperature and pressure and acentric factor.\n\n The density of a liquid is given by:\n\n .. math::\n &\\ln \\frac{P_c}{\\rho RT} = \\ln U^{(0)} + \\omega\\ln U^{(1)}\n\n &\\ln U^{(0)} = 1.396 44 - 24.076T_r+ 102.615T_r^2\n -255.719T_r^3+355.805T_r^4-256.671T_r^5 + 75.1088T_r^6\n\n &\\ln U^{(1)} = 13.4412 - 135.7437 T_r + 533.380T_r^2-\n 1091.453T_r^3+1231.43T_r^4 - 728.227T_r^5 + 176.737T_r^6\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n omega : float\n Acentric factor for fluid, [-]\n\n Returns\n -------\n Vm : float\n Saturated liquid molar volume, [mol/m^3]\n\n Notes\n -----\n Claimed inadequate by others.\n\n An interpolation table for ln U values are used from Tr = 0.98 - 1.000.\n Has terrible behavior at low reduced temperatures.\n\n Examples\n --------\n Pentane\n\n >>> Bhirud_normal(280.0, 469.7, 33.7E5, 0.252)\n 0.00011249654029488583\n\n References\n ----------\n .. [1] Bhirud, Vasant L. \"Saturated Liquid Densities of Normal Fluids.\"\n AIChE Journal 24, no. 6 (November 1, 1978): 1127-31.\n doi:10.1002/aic.690240630\n '''\n Tr = T/Tc\n if Tr <= 0.98:\n lnU0 = 1.39644 - 24.076*Tr + 102.615*Tr**2 - 255.719*Tr**3 \\\n + 355.805*Tr**4 - 256.671*Tr**5 + 75.1088*Tr**6\n lnU1 = 13.4412 - 135.7437*Tr + 533.380*Tr**2-1091.453*Tr**3 \\\n + 1231.43*Tr**4 - 728.227*Tr**5 + 176.737*Tr**6\n elif Tr > 1:\n raise Exception('Critical phase, correlation does not apply')\n else:\n lnU0 = Bhirud_normal_lnU0_interp(Tr)\n lnU1 = Bhirud_normal_lnU1_interp(Tr)\n\n Unonpolar = exp(lnU0 + omega*lnU1)\n Vm = Unonpolar*R*T/Pc\n return Vm", "response": "r Calculates the saturation liquid density using the Bhirud method."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef SNM0(T, Tc, Vc, omega, delta_SRK=None):\n r'''Calculates saturated liquid density using the Mchaweh, Moshfeghian\n model [1]_. Designed for simple calculations.\n\n .. math::\n V_s = V_c/(1+1.169\\tau^{1/3}+1.818\\tau^{2/3}-2.658\\tau+2.161\\tau^{4/3}\n\n \\tau = 1-\\frac{(T/T_c)}{\\alpha_{SRK}}\n\n \\alpha_{SRK} = [1 + m(1-\\sqrt{T/T_C}]^2\n\n m = 0.480+1.574\\omega-0.176\\omega^2\n\n If the fit parameter `delta_SRK` is provided, the following is used:\n\n .. math::\n V_s = V_C/(1+1.169\\tau^{1/3}+1.818\\tau^{2/3}-2.658\\tau+2.161\\tau^{4/3})\n /\\left[1+\\delta_{SRK}(\\alpha_{SRK}-1)^{1/3}\\right]\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Vc : float\n Critical volume of fluid [m^3/mol]\n omega : float\n Acentric factor for fluid, [-]\n delta_SRK : float, optional\n Fitting parameter [-]\n\n Returns\n -------\n Vs : float\n Saturation liquid volume, [m^3/mol]\n\n Notes\n -----\n 73 fit parameters have been gathered from the article.\n\n Examples\n --------\n Argon, without the fit parameter and with it. Tabulated result in Perry's\n is 3.4613e-05. The fit increases the error on this occasion.\n\n >>> SNM0(121, 150.8, 7.49e-05, -0.004)\n 3.4402256402733416e-05\n >>> SNM0(121, 150.8, 7.49e-05, -0.004, -0.03259620)\n 3.493288100008123e-05\n\n References\n ----------\n .. [1] Mchaweh, A., A. Alsaygh, Kh. Nasrifar, and M. Moshfeghian.\n \"A Simplified Method for Calculating Saturated Liquid Densities.\"\n Fluid Phase Equilibria 224, no. 2 (October 1, 2004): 157-67.\n doi:10.1016/j.fluid.2004.06.054\n '''\n Tr = T/Tc\n m = 0.480 + 1.574*omega - 0.176*omega*omega\n alpha_SRK = (1. + m*(1. - Tr**0.5))**2\n tau = 1. - Tr/alpha_SRK\n\n rho0 = 1. + 1.169*tau**(1/3.) + 1.818*tau**(2/3.) - 2.658*tau + 2.161*tau**(4/3.)\n V0 = 1./rho0\n\n if not delta_SRK:\n return Vc*V0\n else:\n return Vc*V0/(1. + delta_SRK*(alpha_SRK - 1.)**(1/3.))", "response": "r Returns a string that is a simple formula for calculating the saturated liquid density of a given temperature and critical volume."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef COSTALD_compressed(T, P, Psat, Tc, Pc, omega, Vs):\n r'''Calculates compressed-liquid volume, using the COSTALD [1]_ CSP\n method and a chemical's critical properties.\n\n The molar volume of a liquid is given by:\n\n .. math::\n V = V_s\\left( 1 - C \\ln \\frac{B + P}{B + P^{sat}}\\right)\n\n \\frac{B}{P_c} = -1 + a\\tau^{1/3} + b\\tau^{2/3} + d\\tau + e\\tau^{4/3}\n\n e = \\exp(f + g\\omega_{SRK} + h \\omega_{SRK}^2)\n\n C = j + k \\omega_{SRK}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n P : float\n Pressure of fluid [Pa]\n Psat : float\n Saturation pressure of the fluid [Pa]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n omega : float\n (ideally SRK) Acentric factor for fluid, [-]\n This parameter is alternatively a fit parameter.\n Vs : float\n Saturation liquid volume, [m^3/mol]\n\n Returns\n -------\n V_dense : float\n High-pressure liquid volume, [m^3/mol]\n\n Notes\n -----\n Original equation was in terms of density, but it is converted here.\n\n The example is from DIPPR, and exactly correct.\n This is DIPPR Procedure 4C: Method for Estimating the Density of Pure\n Organic Liquids under Pressure.\n\n Examples\n --------\n >>> COSTALD_compressed(303., 9.8E7, 85857.9, 466.7, 3640000.0, 0.281, 0.000105047)\n 9.287482879788506e-05\n\n References\n ----------\n .. [1] Thomson, G. H., K. R. Brobst, and R. W. Hankinson. \"An Improved\n Correlation for Densities of Compressed Liquids and Liquid Mixtures.\"\n AIChE Journal 28, no. 4 (July 1, 1982): 671-76. doi:10.1002/aic.690280420\n '''\n a = -9.070217\n b = 62.45326\n d = -135.1102\n f = 4.79594\n g = 0.250047\n h = 1.14188\n j = 0.0861488\n k = 0.0344483\n tau = 1 - T/Tc\n e = exp(f + g*omega + h*omega**2)\n C = j + k*omega\n B = Pc*(-1 + a*tau**(1/3.) + b*tau**(2/3.) + d*tau + e*tau**(4/3.))\n return Vs*(1 - C*log((B + P)/(B + Psat)))", "response": "r Calculates the compressed - liquid volume of a given temperature pressure temperature and critical pressure."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Amgat(xs, Vms):\n r'''Calculate mixture liquid density using the Amgat mixing rule.\n Highly inacurate, but easy to use. Assumes idea liquids with\n no excess volume. Average molecular weight should be used with it to obtain\n density.\n\n .. math::\n V_{mix} = \\sum_i x_i V_i\n\n or in terms of density:\n\n .. math::\n\n \\rho_{mix} = \\sum\\frac{x_i}{\\rho_i}\n\n Parameters\n ----------\n xs : array\n Mole fractions of each component, []\n Vms : array\n Molar volumes of each fluids at conditions [m^3/mol]\n\n Returns\n -------\n Vm : float\n Mixture liquid volume [m^3/mol]\n\n Notes\n -----\n Units are that of the given volumes.\n It has been suggested to use this equation with weight fractions,\n but the results have been less accurate.\n\n Examples\n --------\n >>> Amgat([0.5, 0.5], [4.057e-05, 5.861e-05])\n 4.9590000000000005e-05\n '''\n if not none_and_length_check([xs, Vms]):\n raise Exception('Function inputs are incorrect format')\n return mixing_simple(xs, Vms)", "response": "r Calculates the mixture liquid density using the Amgat mixing rule."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Rackett_mixture(T, xs, MWs, Tcs, Pcs, Zrs):\n r'''Calculate mixture liquid density using the Rackett-derived mixing rule\n as shown in [2]_.\n\n .. math::\n V_m = \\sum_i\\frac{x_i T_{ci}}{MW_i P_{ci}} Z_{R,m}^{(1 + (1 - T_r)^{2/7})} R \\sum_i x_i MW_i\n\n Parameters\n ----------\n T : float\n Temperature of liquid [K]\n xs: list\n Mole fractions of each component, []\n MWs : list\n Molecular weights of each component [g/mol]\n Tcs : list\n Critical temperatures of each component [K]\n Pcs : list\n Critical pressures of each component [Pa]\n Zrs : list\n Rackett parameters of each component []\n\n Returns\n -------\n Vm : float\n Mixture liquid volume [m^3/mol]\n\n Notes\n -----\n Model for pure compounds in [1]_ forms the basis for this model, shown in\n [2]_. Molecular weights are used as weighing by such has been found to\n provide higher accuracy in [2]_. The model can also be used without\n molecular weights, but results are somewhat different.\n\n As with the Rackett model, critical compressibilities may be used if\n Rackett parameters have not been regressed.\n\n Critical mixture temperature, and compressibility are all obtained with\n simple mixing rules.\n\n Examples\n --------\n Calculation in [2]_ for methanol and water mixture. Result matches example.\n\n >>> Rackett_mixture(T=298., xs=[0.4576, 0.5424], MWs=[32.04, 18.01], Tcs=[512.58, 647.29], Pcs=[8.096E6, 2.209E7], Zrs=[0.2332, 0.2374])\n 2.625288603174508e-05\n\n References\n ----------\n .. [1] Rackett, Harold G. \"Equation of State for Saturated Liquids.\"\n Journal of Chemical & Engineering Data 15, no. 4 (1970): 514-517.\n doi:10.1021/je60047a012\n .. [2] Danner, Ronald P, and Design Institute for Physical Property Data.\n Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982.\n '''\n if not none_and_length_check([xs, MWs, Tcs, Pcs, Zrs]):\n raise Exception('Function inputs are incorrect format')\n Tc = mixing_simple(xs, Tcs)\n Zr = mixing_simple(xs, Zrs)\n MW = mixing_simple(xs, MWs)\n Tr = T/Tc\n bigsum = sum(xs[i]*Tcs[i]/Pcs[i]/MWs[i] for i in range(len(xs)))\n return (R*bigsum*Zr**(1. + (1. - Tr)**(2/7.)))*MW", "response": "r Calculates the mixture liquid density using the Rackett - derived mixing rule."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef COSTALD_mixture(xs, T, Tcs, Vcs, omegas):\n r'''Calculate mixture liquid density using the COSTALD CSP method.\n\n A popular and accurate estimation method. If possible, fit parameters are\n used; alternatively critical properties work well.\n\n The mixing rules giving parameters for the pure component COSTALD\n equation are:\n\n .. math::\n T_{cm} = \\frac{\\sum_i\\sum_j x_i x_j (V_{ij}T_{cij})}{V_m}\n\n V_m = 0.25\\left[ \\sum x_i V_i + 3(\\sum x_i V_i^{2/3})(\\sum_i x_i V_i^{1/3})\\right]\n\n V_{ij}T_{cij} = (V_iT_{ci}V_{j}T_{cj})^{0.5}\n\n \\omega = \\sum_i z_i \\omega_i\n\n Parameters\n ----------\n xs: list\n Mole fractions of each component\n T : float\n Temperature of fluid [K]\n Tcs : list\n Critical temperature of fluids [K]\n Vcs : list\n Critical volumes of fluids [m^3/mol].\n This parameter is alternatively a fit parameter\n omegas : list\n (ideally SRK) Acentric factor of all fluids, [-]\n This parameter is alternatively a fit parameter.\n\n Returns\n -------\n Vs : float\n Saturation liquid mixture volume\n\n Notes\n -----\n Range: 0.25 < Tr < 0.95, often said to be to 1.0\n No example has been found.\n Units are that of critical or fit constant volume.\n\n Examples\n --------\n >>> COSTALD_mixture([0.4576, 0.5424], 298., [512.58, 647.29],[0.000117, 5.6e-05], [0.559,0.344] )\n 2.706588773271354e-05\n\n References\n ----------\n .. [1] Hankinson, Risdon W., and George H. Thomson. \"A New Correlation for\n Saturated Densities of Liquids and Their Mixtures.\" AIChE Journal\n 25, no. 4 (1979): 653-663. doi:10.1002/aic.690250412\n '''\n cmps = range(len(xs))\n if not none_and_length_check([xs, Tcs, Vcs, omegas]):\n raise Exception('Function inputs are incorrect format')\n sum1 = sum([xi*Vci for xi, Vci in zip(xs, Vcs)])\n sum2 = sum([xi*Vci**(2/3.) for xi, Vci in zip(xs, Vcs)])\n sum3 = sum([xi*Vci**(1/3.) for xi, Vci in zip(xs, Vcs)])\n Vm = 0.25*(sum1 + 3.*sum2*sum3)\n VijTcij = [[(Tcs[i]*Tcs[j]*Vcs[i]*Vcs[j])**0.5 for j in cmps] for i in cmps]\n omega = mixing_simple(xs, omegas)\n Tcm = sum([xs[i]*xs[j]*VijTcij[i][j]/Vm for j in cmps for i in cmps])\n return COSTALD(T, Tcm, Vm, omega)", "response": "r Calculates the mixture liquid density using the COSTALD CSP method."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef calculate(self, T, P, zs, ws, method):\n r'''Method to calculate molar volume of a liquid mixture at \n temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n `ws` with a given method.\n\n This method has no exception handling; see `mixture_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the property, [K]\n P : float\n Pressure at which to calculate the property, [Pa]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n method : str\n Name of the method to use\n\n Returns\n -------\n Vm : float\n Molar volume of the liquid mixture at the given conditions, \n [m^3/mol]\n '''\n if method == SIMPLE:\n Vms = [i(T, P) for i in self.VolumeLiquids]\n return Amgat(zs, Vms)\n elif method == COSTALD_MIXTURE:\n return COSTALD_mixture(zs, T, self.Tcs, self.Vcs, self.omegas)\n elif method == COSTALD_MIXTURE_FIT:\n return COSTALD_mixture(zs, T, self.Tcs, self.COSTALD_Vchars, self.COSTALD_omegas)\n elif method == RACKETT:\n return Rackett_mixture(T, zs, self.MWs, self.Tcs, self.Pcs, self.Zcs)\n elif method == RACKETT_PARAMETERS:\n return Rackett_mixture(T, zs, self.MWs, self.Tcs, self.Pcs, self.Z_RAs)\n elif method == LALIBERTE:\n ws = list(ws) ; ws.pop(self.index_w)\n rho = Laliberte_density(T, ws, self.wCASs)\n MW = mixing_simple(zs, self.MWs)\n return rho_to_Vm(rho, MW)\n else:\n raise Exception('Method not valid')", "response": "r Method to calculate the molar volume of a liquid mixture at \n temperature pressure P mole fractions zs and weight fractions ws."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef calculate_P(self, T, P, method):\n r'''Method to calculate pressure-dependent gas molar volume at\n temperature `T` and pressure `P` with a given method.\n\n This method has no exception handling; see `TP_dependent_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate molar volume, [K]\n P : float\n Pressure at which to calculate molar volume, [K]\n method : str\n Name of the method to use\n\n Returns\n -------\n Vm : float\n Molar volume of the gas at T and P, [m^3/mol]\n '''\n if method == EOS:\n self.eos[0] = self.eos[0].to_TP(T=T, P=P)\n Vm = self.eos[0].V_g\n elif method == TSONOPOULOS_EXTENDED:\n B = BVirial_Tsonopoulos_extended(T, self.Tc, self.Pc, self.omega, dipole=self.dipole)\n Vm = ideal_gas(T, P) + B\n elif method == TSONOPOULOS:\n B = BVirial_Tsonopoulos(T, self.Tc, self.Pc, self.omega)\n Vm = ideal_gas(T, P) + B\n elif method == ABBOTT:\n B = BVirial_Abbott(T, self.Tc, self.Pc, self.omega)\n Vm = ideal_gas(T, P) + B\n elif method == PITZER_CURL:\n B = BVirial_Pitzer_Curl(T, self.Tc, self.Pc, self.omega)\n Vm = ideal_gas(T, P) + B\n elif method == CRC_VIRIAL:\n a1, a2, a3, a4, a5 = self.CRC_VIRIAL_coeffs\n t = 298.15/T - 1.\n B = (a1 + a2*t + a3*t**2 + a4*t**3 + a5*t**4)/1E6\n Vm = ideal_gas(T, P) + B\n elif method == IDEAL:\n Vm = ideal_gas(T, P)\n elif method == COOLPROP:\n Vm = 1./PropsSI('DMOLAR', 'T', T, 'P', P, self.CASRN)\n elif method in self.tabular_data:\n Vm = self.interpolate_P(T, P, method)\n return Vm", "response": "r Method to calculate the pressure - dependent gas molar volume at a given temperature T and pressure P."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef calculate(self, T, P, zs, ws, method):\n r'''Method to calculate molar volume of a gas mixture at \n temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n `ws` with a given method.\n\n This method has no exception handling; see `mixture_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the property, [K]\n P : float\n Pressure at which to calculate the property, [Pa]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n method : str\n Name of the method to use\n\n Returns\n -------\n Vm : float\n Molar volume of the gas mixture at the given conditions, [m^3/mol]\n '''\n if method == SIMPLE:\n Vms = [i(T, P) for i in self.VolumeGases]\n return mixing_simple(zs, Vms)\n elif method == IDEAL:\n return ideal_gas(T, P)\n elif method == EOS:\n self.eos[0] = self.eos[0].to_TP_zs(T=T, P=P, zs=zs)\n return self.eos[0].V_g\n else:\n raise Exception('Method not valid')", "response": "r Method to calculate the molar volume of a gas mixture at \n temperature pressure mole fractions zs and weight fractions of all species in the mixture at a given time."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef enthalpy_Cpg_Hvap(self):\n r'''Method to calculate the enthalpy of an ideal mixture (no pressure\n effects). This routine is based on \"route A\", where only the gas heat\n capacity and enthalpy of vaporization are used.\n \n The reference temperature is a property of the class; it defaults to\n 298.15 K.\n \n For a pure gas mixture:\n \n .. math::\n H = \\sum_i z_i \\cdot \\int_{T_{ref}}^T C_{p}^{ig}(T) dT\n \n For a pure liquid mixture:\n \n .. math::\n H = \\sum_i z_i \\left( \\int_{T_{ref}}^T C_{p}^{ig}(T) dT + H_{vap, i}(T) \\right)\n \n For a vapor-liquid mixture:\n \n .. math::\n H = \\sum_i z_i \\cdot \\int_{T_{ref}}^T C_{p}^{ig}(T) dT\n + \\sum_i x_i\\left(1 - \\frac{V}{F}\\right)H_{vap, i}(T)\n\n Returns\n -------\n H : float\n Enthalpy of the mixture with respect to the reference temperature,\n [J/mol]\n \n Notes\n -----\n The object must be flashed before this routine can be used. It \n depends on the properties T, zs, xs, V_over_F, HeatCapacityGases, \n EnthalpyVaporizations, and.\n '''\n H = 0\n T = self.T\n if self.phase == 'g':\n for i in self.cmps:\n H += self.zs[i]*self.HeatCapacityGases[i].T_dependent_property_integral(self.T_REF_IG, T)\n elif self.phase == 'l':\n for i in self.cmps:\n # No further contribution needed\n Hg298_to_T = self.HeatCapacityGases[i].T_dependent_property_integral(self.T_REF_IG, T)\n Hvap = self.EnthalpyVaporizations[i](T) # Do the transition at the temperature of the liquid\n if Hvap is None:\n Hvap = 0 # Handle the case of a package predicting a transition past the Tc\n H += self.zs[i]*(Hg298_to_T - Hvap)\n elif self.phase == 'l/g':\n for i in self.cmps:\n Hg298_to_T_zi = self.zs[i]*self.HeatCapacityGases[i].T_dependent_property_integral(self.T_REF_IG, T)\n Hvap = self.EnthalpyVaporizations[i](T) \n if Hvap is None:\n Hvap = 0 # Handle the case of a package predicting a transition past the Tc\n Hvap_contrib = -self.xs[i]*(1-self.V_over_F)*Hvap\n H += (Hg298_to_T_zi + Hvap_contrib)\n return H", "response": "Method to calculate the enthalpy of an ideal mixture. This routine is based on route A where only the gas heat\n capacity and enthalpy of vaporization effects are used."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef entropy_Cpg_Hvap(self):\n r'''Method to calculate the entropy of an ideal mixture. This routine \n is based on \"route A\", where only the gas heat capacity and enthalpy of\n vaporization are used.\n \n The reference temperature and pressure are properties of the class; it \n defaults to 298.15 K and 101325 Pa.\n \n There is a contribution due to mixing:\n \n .. math::\n \\Delta S_{mixing} = -R\\sum_i z_i \\log(z_i) \n \n The ideal gas pressure contribution is:\n \n .. math::\n \\Delta S_{P} = -R\\log\\left(\\frac{P}{P_{ref}}\\right)\n \n For a liquid mixture or a partially liquid mixture, the entropy\n contribution is not so strong - all such pressure effects find that\n expression capped at the vapor pressure, as shown in [1]_.\n \n .. math::\n \\Delta S_{P} = - \\sum_i x_i\\left(1 - \\frac{V}{F}\\right) \n R\\log\\left(\\frac{P_{sat, i}}{P_{ref}}\\right) - \\sum_i y_i\\left(\n \\frac{V}{F}\\right) R\\log\\left(\\frac{P}{P_{ref}}\\right)\n \n These expressions are combined with the standard heat capacity and \n enthalpy of vaporization expressions to calculate the total entropy:\n \n For a pure gas mixture:\n \n .. math::\n S = \\Delta S_{mixing} + \\Delta S_{P} + \\sum_i z_i \\cdot\n \\int_{T_{ref}}^T \\frac{C_{p}^{ig}(T)}{T} dT\n \n For a pure liquid mixture:\n \n .. math::\n S = \\Delta S_{mixing} + \\Delta S_{P} + \\sum_i z_i \\left( \n \\int_{T_{ref}}^T \\frac{C_{p}^{ig}(T)}{T} dT + \\frac{H_{vap, i}\n (T)}{T} \\right)\n \n For a vapor-liquid mixture:\n \n .. math::\n S = \\Delta S_{mixing} + \\Delta S_{P} + \\sum_i z_i \\cdot \n \\int_{T_{ref}}^T \\frac{C_{p}^{ig}(T)}{T} dT + \\sum_i x_i\\left(1\n - \\frac{V}{F}\\right)\\frac{H_{vap, i}(T)}{T}\n \n Returns\n -------\n S : float\n Entropy of the mixture with respect to the reference temperature,\n [J/mol/K]\n \n Notes\n -----\n The object must be flashed before this routine can be used. It \n depends on the properties T, P, zs, V_over_F, HeatCapacityGases, \n EnthalpyVaporizations, VaporPressures, and xs.\n \n References\n ----------\n .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n '''\n S = 0\n T = self.T\n P = self.P\n S -= R*sum([zi*log(zi) for zi in self.zs if zi > 0]) # ideal composition entropy composition; chemsep checked\n # Both of the mixing and vapor pressure terms have negative signs\n # Equation 6-4.4b in Poling for the vapor pressure component\n # For liquids above their critical temperatures, Psat is equal to the system P (COCO).\n if self.phase == 'g':\n S -= R*log(P/101325.) # Gas-phase ideal pressure contribution (checked repeatedly)\n for i in self.cmps:\n S += self.HeatCapacityGases[i].T_dependent_property_integral_over_T(298.15, T)\n elif self.phase == 'l':\n Psats = self._Psats(T)\n for i in self.cmps:\n Sg298_to_T = self.HeatCapacityGases[i].T_dependent_property_integral_over_T(298.15, T)\n Hvap = self.EnthalpyVaporizations[i](T)\n if Hvap is None:\n Hvap = 0 # Handle the case of a package predicting a transition past the Tc\n Svap = -Hvap/T # Do the transition at the temperature of the liquid\n S_P = -R*log(Psats[i]/101325.)\n S += self.zs[i]*(Sg298_to_T + Svap + S_P)\n elif self.phase == 'l/g':\n Psats = self._Psats(T)\n S_P_vapor = -R*log(P/101325.) # Gas-phase ideal pressure contribution (checked repeatedly)\n for i in self.cmps:\n Sg298_to_T_zi = self.zs[i]*self.HeatCapacityGases[i].T_dependent_property_integral_over_T(298.15, T)\n Hvap = self.EnthalpyVaporizations[i](T) \n if Hvap is None:\n Hvap = 0 # Handle the case of a package predicting a transition past the Tc\n\n Svap_contrib = -self.xs[i]*(1-self.V_over_F)*Hvap/T\n # Pressure contributions from both phases\n S_P_vapor_i = self.V_over_F*self.ys[i]*S_P_vapor\n S_P_liquid_i = -R*log(Psats[i]/101325.)*(1-self.V_over_F)*self.xs[i]\n S += (Sg298_to_T_zi + Svap_contrib + S_P_vapor_i + S_P_liquid_i)\n return S", "response": "Method to calculate the entropy of an ideal mixture. This method is based on route A and route B and route A and route B and route A."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef load_economic_data():\n global HPV_data\n if HPV_data is not None:\n return None\n global _EPACDRDict, _ECHATonnageDict\n \n '''OECD are chemicals produced by and OECD members in > 1000 tonnes/year.'''\n HPV_data = pd.read_csv(os.path.join(folder, 'HPV 2015 March 3.csv'),\n sep='\\t', index_col=0)\n # 13061-29-2 not valid and removed\n \n _ECHATonnageDict = {}\n with zipfile.ZipFile(os.path.join(folder, 'ECHA Tonnage Bands.csv.zip')) as z:\n with z.open(z.namelist()[0]) as f:\n for line in f.readlines():\n # for some reason, the file must be decoded to UTF8 first\n CAS, band = line.decode(\"utf-8\").strip('\\n').split('\\t')\n if CAS in _ECHATonnageDict:\n if band in _ECHATonnageDict[CAS]:\n pass\n else:\n _ECHATonnageDict[CAS].append(band)\n else:\n _ECHATonnageDict[CAS] = [band]\n \n \n _EPACDRDict = {}\n with open(os.path.join(folder, 'EPA 2012 Chemical Data Reporting.csv')) as f:\n '''EPA summed reported chemical usages. In metric tonnes/year after conversion.\n Many producers keep their date confidential.\n This was originally in terms of lb/year, but rounded to the nearest kg.\n \n '''\n next(f)\n for line in f:\n values = line.rstrip().split('\\t')\n CAS, manufactured, imported, exported = to_num(values)\n _EPACDRDict[CAS] = {\"Manufactured\": manufactured/1000., \"Imported\": imported/1000.,\n \"Exported\": exported/1000.}", "response": "Loads the ePA - 2012 ephemeris chemical data from the file HPV_data."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nlooking up the economic status of a chemical.", "response": "def economic_status(CASRN, Method=None, AvailableMethods=False): # pragma: no cover\n '''Look up the economic status of a chemical.\n\n This API is considered experimental, and is expected to be removed in a\n future release in favor of a more complete object-oriented interface.\n\n >>> pprint(economic_status(CASRN='98-00-0'))\n [\"US public: {'Manufactured': 0.0, 'Imported': 10272.711, 'Exported': 184.127}\",\n u'10,000 - 100,000 tonnes per annum',\n 'OECD HPV Chemicals']\n\n >>> economic_status(CASRN='13775-50-3') # SODIUM SESQUISULPHATE\n []\n >>> economic_status(CASRN='98-00-0', Method='OECD high production volume chemicals')\n 'OECD HPV Chemicals'\n >>> economic_status(CASRN='98-01-1', Method='European Chemicals Agency Total Tonnage Bands')\n [u'10,000 - 100,000 tonnes per annum']\n '''\n load_economic_data()\n CASi = CAS2int(CASRN)\n\n def list_methods():\n methods = []\n methods.append('Combined')\n if CASRN in _EPACDRDict:\n methods.append(EPACDR)\n if CASRN in _ECHATonnageDict:\n methods.append(ECHA)\n if CASi in HPV_data.index:\n methods.append(OECD)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n if Method == EPACDR:\n status = 'US public: ' + str(_EPACDRDict[CASRN])\n elif Method == ECHA:\n status = _ECHATonnageDict[CASRN]\n elif Method == OECD:\n status = 'OECD HPV Chemicals'\n elif Method == 'Combined':\n status = []\n if CASRN in _EPACDRDict:\n status += ['US public: ' + str(_EPACDRDict[CASRN])]\n if CASRN in _ECHATonnageDict:\n status += _ECHATonnageDict[CASRN]\n if CASi in HPV_data.index:\n status += ['OECD HPV Chemicals']\n elif Method == NONE:\n status = None\n else:\n raise Exception('Failure in in function')\n return status"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef BVirial_Tsonopoulos_extended(T, Tc, Pc, omega, a=0, b=0, species_type='', \n dipole=0, order=0):\n r'''Calculates the second virial coefficient using the\n comprehensive model in [1]_. See the notes for the calculation of `a` and\n `b`.\n\n .. math::\n \\frac{BP_c}{RT_c} = B^{(0)} + \\omega B^{(1)} + a B^{(2)} + b B^{(3)}\n \n B^{(0)}=0.1445-0.33/T_r-0.1385/T_r^2-0.0121/T_r^3\n\n B^{(1)} = 0.0637+0.331/T_r^2-0.423/T_r^3 -0.423/T_r^3 - 0.008/T_r^8\n \n B^{(2)} = 1/T_r^6\n\n B^{(3)} = -1/T_r^8\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of the fluid [Pa]\n omega : float\n Acentric factor for fluid, [-]\n a : float, optional\n Fit parameter, calculated based on species_type if a is not given and\n species_type matches on of the supported chemical classes.\n b : float, optional\n Fit parameter, calculated based on species_type if a is not given and\n species_type matches on of the supported chemical classes.\n species_type : str, optional\n One of .\n dipole : float\n dipole moment, optional, [Debye]\n order : int, optional\n Order of the calculation. 0 for the calculation of B itself; for 1/2/3, \n the first/second/third derivative of B with respect to temperature; and \n for -1/-2, the first/second indefinite integral of B with respect to \n temperature. No other integrals or derivatives are implemented, and an \n exception will be raised if any other order is given.\n\n Returns\n -------\n B : float\n Second virial coefficient in density form or its integral/derivative if\n specified, [m^3/mol or m^3/mol/K^order]\n\n Notes\n -----\n Analytical models for derivatives and integrals are available for orders\n -2, -1, 1, 2, and 3, all obtained with SymPy.\n\n\n To calculate `a` or `b`, the following rules are used:\n\n For 'simple' or 'normal' fluids:\n \n .. math::\n a = 0\n \n b = 0\n\n For 'ketone', 'aldehyde', 'alkyl nitrile', 'ether', 'carboxylic acid',\n or 'ester' types of chemicals:\n \n .. math::\n a = -2.14\\times 10^{-4} \\mu_r - 4.308 \\times 10^{-21} (\\mu_r)^8\n \n b = 0\n \n For 'alkyl halide', 'mercaptan', 'sulfide', or 'disulfide' types of \n chemicals:\n\n .. math::\n a = -2.188\\times 10^{-4} (\\mu_r)^4 - 7.831 \\times 10^{-21} (\\mu_r)^8\n \n b = 0\n\n For 'alkanol' types of chemicals (except methanol):\n \n .. math::\n a = 0.0878\n \n b = 0.00908 + 0.0006957 \\mu_r\n \n For methanol:\n \n .. math::\n a = 0.0878\n \n b = 0.0525\n \n For water:\n \n .. math::\n a = -0.0109\n \n b = 0\n \n If required, the form of dipole moment used in the calculation of some\n types of `a` and `b` values is as follows:\n \n .. math::\n \\mu_r = 100000\\frac{\\mu^2(Pc/101325.0)}{Tc^2}\n\n\n For first temperature derivative of B:\n \n .. math::\n \\frac{d B^{(0)}}{dT} = \\frac{33 Tc}{100 T^{2}} + \\frac{277 Tc^{2}}{1000 T^{3}} + \\frac{363 Tc^{3}}{10000 T^{4}} + \\frac{607 Tc^{8}}{125000 T^{9}}\n\n \\frac{d B^{(1)}}{dT} = - \\frac{331 Tc^{2}}{500 T^{3}} + \\frac{1269 Tc^{3}}{1000 T^{4}} + \\frac{8 Tc^{8}}{125 T^{9}}\n\n \\frac{d B^{(2)}}{dT} = - \\frac{6 Tc^{6}}{T^{7}}\n\n \\frac{d B^{(3)}}{dT} = \\frac{8 Tc^{8}}{T^{9}}\n\n For the second temperature derivative of B:\n \n .. math::\n \\frac{d^2 B^{(0)}}{dT^2} = - \\frac{3 Tc}{125000 T^{3}} \\left(27500 + \\frac{34625 Tc}{T} + \\frac{6050 Tc^{2}}{T^{2}} + \\frac{1821 Tc^{7}}{T^{7}}\\right)\n\n \\frac{d^2 B^{(1)}}{dT^2} = \\frac{3 Tc^{2}}{500 T^{4}} \\left(331 - \\frac{846 Tc}{T} - \\frac{96 Tc^{6}}{T^{6}}\\right)\n\n \\frac{d^2 B^{(2)}}{dT^2} = \\frac{42 Tc^{6}}{T^{8}}\n\n \\frac{d^2 B^{(3)}}{dT^2} = - \\frac{72 Tc^{8}}{T^{10}}\n\n For the third temperature derivative of B:\n \n .. math::\n \\frac{d^3 B^{(0)}}{dT^3} = \\frac{3 Tc}{12500 T^{4}} \\left(8250 + \\frac{13850 Tc}{T} + \\frac{3025 Tc^{2}}{T^{2}} + \\frac{1821 Tc^{7}}{T^{7}}\\right)\n\n \\frac{d^3 B^{(1)}}{dT^3} = \\frac{3 Tc^{2}}{250 T^{5}} \\left(-662 + \\frac{2115 Tc}{T} + \\frac{480 Tc^{6}}{T^{6}}\\right)\n\n \\frac{d^3 B^{(2)}}{dT^3} = - \\frac{336 Tc^{6}}{T^{9}}\n\n \\frac{d^3 B^{(3)}}{dT^3} = \\frac{720 Tc^{8}}{T^{11}}\n\n For the first indefinite integral of B:\n \n .. math::\n \\int{B^{(0)}} dT = \\frac{289 T}{2000} - \\frac{33 Tc}{100} \\log{\\left (T \\right )} + \\frac{1}{7000000 T^{7}} \\left(969500 T^{6} Tc^{2} + 42350 T^{5} Tc^{3} + 607 Tc^{8}\\right)\n \n \\int{B^{(1)}} dT = \\frac{637 T}{10000} - \\frac{1}{70000 T^{7}} \\left(23170 T^{6} Tc^{2} - 14805 T^{5} Tc^{3} - 80 Tc^{8}\\right)\n\n \\int{B^{(2)}} dT = - \\frac{Tc^{6}}{5 T^{5}}\n\n \\int{B^{(3)}} dT = \\frac{Tc^{8}}{7 T^{7}}\n\n For the second indefinite integral of B:\n\n .. math::\n \\int\\int B^{(0)} dT dT = \\frac{289 T^{2}}{4000} - \\frac{33 T}{100} Tc \\log{\\left (T \\right )} + \\frac{33 T}{100} Tc + \\frac{277 Tc^{2}}{2000} \\log{\\left (T \\right )} - \\frac{1}{42000000 T^{6}} \\left(254100 T^{5} Tc^{3} + 607 Tc^{8}\\right)\n \n \\int\\int B^{(1)} dT dT = \\frac{637 T^{2}}{20000} - \\frac{331 Tc^{2}}{1000} \\log{\\left (T \\right )} - \\frac{1}{210000 T^{6}} \\left(44415 T^{5} Tc^{3} + 40 Tc^{8}\\right)\n\n \\int\\int B^{(2)} dT dT = \\frac{Tc^{6}}{20 T^{4}}\n \n \\int\\int B^{(3)} dT dT = - \\frac{Tc^{8}}{42 T^{6}}\n \n Examples\n --------\n Example from Perry's Handbook, 8E, p2-499. Matches to a decimal place.\n\n >>> BVirial_Tsonopoulos_extended(430., 405.65, 11.28E6, 0.252608, a=0, b=0, species_type='ketone', dipole=1.469)\n -9.679715056695323e-05\n\n References\n ----------\n .. [1] Tsonopoulos, C., and J. L. Heidman. \"From the Virial to the Cubic\n Equation of State.\" Fluid Phase Equilibria 57, no. 3 (1990): 261-76.\n doi:10.1016/0378-3812(90)85126-U\n .. [2] Tsonopoulos, Constantine, and John H. Dymond. \"Second Virial\n Coefficients of Normal Alkanes, Linear 1-Alkanols (and Water), Alkyl\n Ethers, and Their Mixtures.\" Fluid Phase Equilibria, International\n Workshop on Vapour-Liquid Equilibria and Related Properties in Binary\n and Ternary Mixtures of Ethers, Alkanes and Alkanols, 133, no. 1-2\n (June 1997): 11-34. doi:10.1016/S0378-3812(97)00058-7.\n '''\n Tr = T/Tc\n if order == 0:\n B0 = 0.1445 - 0.33/Tr - 0.1385/Tr**2 - 0.0121/Tr**3 - 0.000607/Tr**8\n B1 = 0.0637 + 0.331/Tr**2 - 0.423/Tr**3 - 0.008/Tr**8\n B2 = 1./Tr**6\n B3 = -1./Tr**8\n elif order == 1:\n B0 = 33*Tc/(100*T**2) + 277*Tc**2/(1000*T**3) + 363*Tc**3/(10000*T**4) + 607*Tc**8/(125000*T**9)\n B1 = -331*Tc**2/(500*T**3) + 1269*Tc**3/(1000*T**4) + 8*Tc**8/(125*T**9)\n B2 = -6.0*Tc**6/T**7\n B3 = 8.0*Tc**8/T**9\n elif order == 2:\n B0 = -3*Tc*(27500 + 34625*Tc/T + 6050*Tc**2/T**2 + 1821*Tc**7/T**7)/(125000*T**3)\n B1 = 3*Tc**2*(331 - 846*Tc/T - 96*Tc**6/T**6)/(500*T**4)\n B2 = 42.0*Tc**6/T**8\n B3 = -72.0*Tc**8/T**10\n elif order == 3:\n B0 = 3*Tc*(8250 + 13850*Tc/T + 3025*Tc**2/T**2 + 1821*Tc**7/T**7)/(12500*T**4)\n B1 = 3*Tc**2*(-662 + 2115*Tc/T + 480*Tc**6/T**6)/(250*T**5)\n B2 = -336.0*Tc**6/T**9\n B3 = 720.0*Tc**8/T**11\n elif order == -1:\n B0 = 289*T/2000. - 33*Tc*log(T)/100. + (969500*T**6*Tc**2 + 42350*T**5*Tc**3 + 607*Tc**8)/(7000000.*T**7)\n B1 = 637*T/10000. - (23170*T**6*Tc**2 - 14805*T**5*Tc**3 - 80*Tc**8)/(70000.*T**7)\n B2 = -Tc**6/(5*T**5)\n B3 = Tc**8/(7*T**7)\n elif order == -2:\n B0 = 289*T**2/4000. - 33*T*Tc*log(T)/100. + 33*T*Tc/100. + 277*Tc**2*log(T)/2000. - (254100*T**5*Tc**3 + 607*Tc**8)/(42000000.*T**6)\n B1 = 637*T**2/20000. - 331*Tc**2*log(T)/1000. - (44415*T**5*Tc**3 + 40*Tc**8)/(210000.*T**6)\n B2 = Tc**6/(20*T**4)\n B3 = -Tc**8/(42*T**6)\n else: \n raise Exception('Only orders -2, -1, 0, 1, 2 and 3 are supported.')\n if a == 0 and b == 0 and species_type != '':\n if species_type == 'simple' or species_type == 'normal':\n a, b = 0, 0\n elif species_type == 'methyl alcohol':\n a, b = 0.0878, 0.0525\n elif species_type == 'water':\n a, b = -0.0109, 0\n elif dipole != 0 and Tc != 0 and Pc != 0:\n dipole_r = 1E5*dipole**2*(Pc/101325.0)/Tc**2\n\n if (species_type == 'ketone' or species_type == 'aldehyde'\n or species_type == 'alkyl nitrile' or species_type == 'ether'\n or species_type == 'carboxylic acid' or species_type == 'ester'):\n a, b = -2.14E-4*dipole_r-4.308E-21*dipole_r**8, 0\n elif (species_type == 'alkyl halide' or species_type == 'mercaptan'\n or species_type == 'sulfide' or species_type == 'disulfide'):\n a, b = -2.188E-4*dipole_r**4-7.831E-21*dipole_r**8, 0\n\n elif species_type == 'alkanol':\n a, b = 0.0878, 0.00908+0.0006957*dipole_r\n Br = B0 + omega*B1 + a*B2 + b*B3\n return Br*R*Tc/Pc", "response": "r Returns the second virial coefficient using the BVirial_Tsonopoulos_extended method."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Tb(counts):\n r'''Estimates the normal boiling temperature of an organic compound \n using the Joback method as a function of chemical structure only.\n \n .. math::\n T_b = 198.2 + \\sum_i {T_{b,i}}\n \n For 438 compounds tested by Joback, the absolute average error was\n 12.91 K and standard deviation was 17.85 K; the average relative error\n was 3.6%. \n \n Parameters\n ----------\n counts : dict\n Dictionary of Joback groups present (numerically indexed) and their\n counts, [-]\n\n Returns\n -------\n Tb : float\n Estimated normal boiling temperature, [K]\n \n Examples\n --------\n >>> Joback.Tb({1: 2, 24: 1})\n 322.11\n ''' \n tot = 0.0\n for group, count in counts.items():\n tot += joback_groups_id_dict[group].Tb*count\n Tb = 198.2 + tot\n return Tb", "response": "Estimate the normal boiling temperature of an organic compound \n using Joback s method."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nestimating the melting temperature of an organic compound using Joback method.", "response": "def Tm(counts):\n r'''Estimates the melting temperature of an organic compound using the \n Joback method as a function of chemical structure only.\n \n .. math::\n T_m = 122.5 + \\sum_i {T_{m,i}}\n \n For 388 compounds tested by Joback, the absolute average error was\n 22.6 K and standard deviation was 24.68 K; the average relative error\n was 11.2%. \n\n Parameters\n ----------\n counts : dict\n Dictionary of Joback groups present (numerically indexed) and their\n counts, [-]\n\n Returns\n -------\n Tm : float\n Estimated melting temperature, [K]\n \n Examples\n --------\n >>> Joback.Tm({1: 2, 24: 1})\n 173.5\n ''' \n tot = 0.0\n for group, count in counts.items():\n tot += joback_groups_id_dict[group].Tm*count\n Tm = 122.5 + tot\n return Tm"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Tc(counts, Tb=None):\n r'''Estimates the critcal temperature of an organic compound using the \n Joback method as a function of chemical structure only, or optionally\n improved by using an experimental boiling point. If the experimental\n boiling point is not provided it will be estimated with the Joback\n method as well.\n \n .. math::\n T_c = T_b \\left[0.584 + 0.965 \\sum_i {T_{c,i}}\n - \\left(\\sum_i {T_{c,i}}\\right)^2 \\right]^{-1}\n \n For 409 compounds tested by Joback, the absolute average error was\n 4.76 K and standard deviation was 6.94 K; the average relative error\n was 0.81%. \n \n Appendix BI of Joback's work lists 409 estimated critical temperatures.\n \n Parameters\n ----------\n counts : dict\n Dictionary of Joback groups present (numerically indexed) and their\n counts, [-]\n Tb : float, optional\n Experimental normal boiling temperature, [K]\n\n Returns\n -------\n Tc : float\n Estimated critical temperature, [K]\n \n Examples\n --------\n >>> Joback.Tc({1: 2, 24: 1}, Tb=322.11)\n 500.5590049525365\n ''' \n if Tb is None:\n Tb = Joback.Tb(counts)\n tot = 0.0\n for group, count in counts.items():\n tot += joback_groups_id_dict[group].Tc*count\n Tc = Tb/(0.584 + 0.965*tot - tot*tot)\n return Tc", "response": "Return the critcal temperature of an organic compound using Joback s method."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Vc(counts):\n r'''Estimates the critcal volume of an organic compound using the \n Joback method as a function of chemical structure only. \n \n .. math::\n V_c = 17.5 + \\sum_i {V_{c,i}}\n \n In the above equation, critical volume is calculated in cm^3/mol; it \n is converted to m^3/mol here.\n \n 310 compounds were used by Joback in this determination, with an \n absolute average error of 7.54 cm^3/mol, standard devaition 13.16\n cm^3/mol, and AARE of 2.27%.\n\n Parameters\n ----------\n counts : dict\n Dictionary of Joback groups present (numerically indexed) and their\n counts, [-]\n\n Returns\n -------\n Vc : float\n Estimated critical volume, [m^3/mol]\n \n Examples\n --------\n >>> Joback.Vc({1: 2, 24: 1})\n 0.0002095\n ''' \n tot = 0.0\n for group, count in counts.items():\n tot += joback_groups_id_dict[group].Vc*count\n Vc = 17.5 + tot\n return Vc*1E-6", "response": "Estimate the critical volume of an organic compound using Joback method."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning an ideal - gas enthalpy of formation at 298. 15 K of an ancestry.", "response": "def Hf(counts):\n r'''Estimates the ideal-gas enthalpy of formation at 298.15 K of an \n organic compound using the Joback method as a function of chemical \n structure only. \n \n .. math::\n H_{formation} = 68.29 + \\sum_i {H_{f,i}}\n \n In the above equation, enthalpy of formation is calculated in kJ/mol; \n it is converted to J/mol here.\n \n 370 compounds were used by Joback in this determination, with an \n absolute average error of 2.2 kcal/mol, standard devaition 2.0 \n kcal/mol, and AARE of 15.2%.\n \n Parameters\n ----------\n counts : dict\n Dictionary of Joback groups present (numerically indexed) and their\n counts, [-]\n\n Returns\n -------\n Hf : float\n Estimated ideal-gas enthalpy of formation at 298.15 K, [J/mol]\n \n Examples\n --------\n >>> Joback.Hf({1: 2, 24: 1})\n -217829.99999999997\n ''' \n tot = 0.0\n for group, count in counts.items():\n tot += joback_groups_id_dict[group].Hform*count\n Hf = 68.29 + tot\n return Hf*1000"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef Gf(counts):\n r'''Estimates the ideal-gas Gibbs energy of formation at 298.15 K of an \n organic compound using the Joback method as a function of chemical \n structure only. \n \n .. math::\n G_{formation} = 53.88 + \\sum {G_{f,i}}\n \n In the above equation, Gibbs energy of formation is calculated in \n kJ/mol; it is converted to J/mol here.\n \n 328 compounds were used by Joback in this determination, with an \n absolute average error of 2.0 kcal/mol, standard devaition 4.37\n kcal/mol, and AARE of 15.7%.\n\n Parameters\n ----------\n counts : dict\n Dictionary of Joback groups present (numerically indexed) and their\n counts, [-]\n\n Returns\n -------\n Gf : float\n Estimated ideal-gas Gibbs energy of formation at 298.15 K, [J/mol]\n \n Examples\n --------\n >>> Joback.Gf({1: 2, 24: 1})\n -154540.00000000003\n ''' \n tot = 0.0\n for group, count in counts.items():\n tot += joback_groups_id_dict[group].Gform*count\n Gf = 53.88 + tot\n return Gf*1000", "response": "Calculates the ideal - gas Gibbs energy of formation at 298. 15 K of an organic compound."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncalculate the enthalpy of fusion of an organic compound at its melting point using Joback s method.", "response": "def Hfus(counts):\n r'''Estimates the enthalpy of fusion of an organic compound at its \n melting point using the Joback method as a function of chemical \n structure only. \n \n .. math::\n \\Delta H_{fus} = -0.88 + \\sum_i H_{fus,i}\n \n In the above equation, enthalpy of fusion is calculated in \n kJ/mol; it is converted to J/mol here.\n \n For 155 compounds tested by Joback, the absolute average error was\n 485.2 cal/mol and standard deviation was 661.4 cal/mol; the average \n relative error was 38.7%. \n\n Parameters\n ----------\n counts : dict\n Dictionary of Joback groups present (numerically indexed) and their\n counts, [-]\n\n Returns\n -------\n Hfus : float\n Estimated enthalpy of fusion of the compound at its melting point,\n [J/mol]\n \n Examples\n --------\n >>> Joback.Hfus({1: 2, 24: 1})\n 5125.0\n '''\n tot = 0.0\n for group, count in counts.items():\n tot += joback_groups_id_dict[group].Hfus*count\n Hfus = -0.88 + tot\n return Hfus*1000"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Hvap(counts):\n r'''Estimates the enthalpy of vaporization of an organic compound at \n its normal boiling point using the Joback method as a function of \n chemical structure only. \n \n .. math::\n \\Delta H_{vap} = 15.30 + \\sum_i H_{vap,i}\n \n In the above equation, enthalpy of fusion is calculated in \n kJ/mol; it is converted to J/mol here.\n \n For 368 compounds tested by Joback, the absolute average error was\n 303.5 cal/mol and standard deviation was 429 cal/mol; the average \n relative error was 3.88%. \n \n Parameters\n ----------\n counts : dict\n Dictionary of Joback groups present (numerically indexed) and their\n counts, [-]\n\n Returns\n -------\n Hvap : float\n Estimated enthalpy of vaporization of the compound at its normal\n boiling point, [J/mol]\n \n Examples\n --------\n >>> Joback.Hvap({1: 2, 24: 1})\n 29018.0\n '''\n tot = 0.0\n for group, count in counts.items():\n tot += joback_groups_id_dict[group].Hvap*count\n Hvap = 15.3 + tot\n return Hvap*1000", "response": "Calculates the enthalpy of vaporization of an organic compound at \n normal boiling point using Joback s method of Joback method."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef mul_coeffs(counts):\n r'''Computes the liquid phase viscosity Joback coefficients \n of an organic compound using the Joback method as a function of \n chemical structure only. \n \n .. math::\n \\mu_{liq} = \\text{MW} \\exp\\left( \\frac{ \\sum_i \\mu_a - 597.82}{T} \n + \\sum_i \\mu_b - 11.202 \\right)\n \n 288 compounds were used by Joback in this determination. No overall \n error was reported.\n\n The liquid viscosity data used was specified to be at \"several \n temperatures for each compound\" only. A small and unspecified number\n of compounds were used in this estimation.\n\n Parameters\n ----------\n counts : dict\n Dictionary of Joback groups present (numerically indexed) and their\n counts, [-]\n\n Returns\n -------\n coefficients : list[float]\n Coefficients which will result in a liquid viscosity in\n in units of Pa*s, [-]\n \n Examples\n --------\n >>> mu_ab = Joback.mul_coeffs({1: 2, 24: 1})\n >>> mu_ab\n [839.1099999999998, -14.99]\n >>> MW = 58.041864812\n >>> mul = lambda T : MW*exp(mu_ab[0]/T + mu_ab[1])\n >>> mul(300)\n 0.0002940378347162687\n '''\n a, b = 0.0, 0.0\n for group, count in counts.items():\n a += joback_groups_id_dict[group].mua*count\n b += joback_groups_id_dict[group].mub*count\n a -= 597.82\n b -= 11.202\n return [a, b]", "response": "r Returns the liquid phase viscosity in a given set of temperatures for each Joback group."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef Cpig(self, T):\n r'''Computes ideal-gas heat capacity at a specified temperature \n of an organic compound using the Joback method as a function of \n chemical structure only. \n \n .. math::\n C_p^{ig} = \\sum_i a_i - 37.93 + \\left[ \\sum_i b_i + 0.210 \\right] T\n + \\left[ \\sum_i c_i - 3.91 \\cdot 10^{-4} \\right] T^2 \n + \\left[\\sum_i d_i + 2.06 \\cdot 10^{-7}\\right] T^3\n \n Parameters\n ----------\n T : float\n Temperature, [K]\n\n Returns\n -------\n Cpig : float\n Ideal-gas heat capacity, [J/mol/K]\n \n Examples\n --------\n >>> J = Joback('CC(=O)C')\n >>> J.Cpig(300)\n 75.32642000000001\n '''\n if self.calculated_Cpig_coeffs is None:\n self.calculated_Cpig_coeffs = Joback.Cpig_coeffs(self.counts)\n return horner(reversed(self.calculated_Cpig_coeffs), T)", "response": "r Returns the ideal - gas heat capacity at a specified temperature INCLUSIVE WITHOUT A COVERAGE."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Laliberte_viscosity_i(T, w_w, v1, v2, v3, v4, v5, v6):\n r'''Calculate the viscosity of a solute using the form proposed by [1]_\n Parameters are needed, and a temperature. Units are Kelvin and Pa*s.\n\n .. math::\n \\mu_i = \\frac{\\exp\\left( \\frac{v_1(1-w_w)^{v_2}+v_3}{v_4 t +1}\\right)}\n {v_5(1-w_w)^{v_6}+1}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n w_w : float\n Weight fraction of water in the solution\n v1-v6 : floats\n Function fit parameters\n\n Returns\n -------\n mu_i : float\n Solute partial viscosity, Pa*s\n\n Notes\n -----\n Temperature range check is outside of this function.\n Check is performed using NaCl at 5 degC from the first value in [1]_'s spreadsheet.\n\n Examples\n --------\n >>> d = _Laliberte_Viscosity_ParametersDict['7647-14-5']\n >>> Laliberte_viscosity_i(273.15+5, 1-0.005810, d[\"V1\"], d[\"V2\"], d[\"V3\"], d[\"V4\"], d[\"V5\"], d[\"V6\"] )\n 0.004254025533308794\n\n References\n ----------\n .. [1] Laliberte, Marc. \"A Model for Calculating the Heat Capacity of\n Aqueous Solutions, with Updated Density and Viscosity Data.\" Journal of\n Chemical & Engineering Data 54, no. 6 (June 11, 2009): 1725-60.\n doi:10.1021/je8008123\n '''\n t = T-273.15\n mu_i = exp((v1*(1-w_w)**v2 + v3)/(v4*t+1))/(v5*(1-w_w)**v6 + 1)\n return mu_i/1000.", "response": "A function that calculates the viscosity of a solute in a Laliberte system."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Laliberte_density_w(T):\n r'''Calculate the density of water using the form proposed by [1]_.\n No parameters are needed, just a temperature. Units are Kelvin and kg/m^3h.\n\n .. math::\n \\rho_w = \\frac{\\left\\{\\left([(-2.8054253\\times 10^{-10}\\cdot t +\n 1.0556302\\times 10^{-7})t - 4.6170461\\times 10^{-5}]t\n -0.0079870401\\right)t + 16.945176 \\right\\}t + 999.83952}\n {1 + 0.01687985\\cdot t}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n\n Returns\n -------\n rho_w : float\n Water density, [kg/m^3]\n\n Notes\n -----\n Original source not cited\n No temperature range is used.\n\n Examples\n --------\n >>> Laliberte_density_w(298.15)\n 997.0448954179155\n >>> Laliberte_density_w(273.15 + 50)\n 988.0362916114763\n\n References\n ----------\n .. [1] Laliberte, Marc. \"A Model for Calculating the Heat Capacity of\n Aqueous Solutions, with Updated Density and Viscosity Data.\" Journal of\n Chemical & Engineering Data 54, no. 6 (June 11, 2009): 1725-60.\n doi:10.1021/je8008123\n '''\n t = T-273.15\n rho_w = (((((-2.8054253E-10*t + 1.0556302E-7)*t - 4.6170461E-5)*t - 0.0079870401)*t + 16.945176)*t + 999.83952) \\\n / (1 + 0.01687985*t)\n return rho_w", "response": "Calculates the density of water using the form proposed by [ 1 ] Laliberte Marc. A Model for Calculating the Heat Capacity of Aqueous Solutions with Updated Density and Viscosity Data."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Laliberte_density_i(T, w_w, c0, c1, c2, c3, c4):\n r'''Calculate the density of a solute using the form proposed by Laliberte [1]_.\n Parameters are needed, and a temperature, and water fraction. Units are Kelvin and Pa*s.\n\n .. math::\n \\rho_{app,i} = \\frac{(c_0[1-w_w]+c_1)\\exp(10^{-6}[t+c_4]^2)}\n {(1-w_w) + c_2 + c_3 t}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n w_w : float\n Weight fraction of water in the solution\n c0-c4 : floats\n Function fit parameters\n\n Returns\n -------\n rho_i : float\n Solute partial density, [kg/m^3]\n\n Notes\n -----\n Temperature range check is TODO\n\n\n Examples\n --------\n >>> d = _Laliberte_Density_ParametersDict['7647-14-5']\n >>> Laliberte_density_i(273.15+0, 1-0.0037838838, d[\"C0\"], d[\"C1\"], d[\"C2\"], d[\"C3\"], d[\"C4\"])\n 3761.8917585699983\n\n References\n ----------\n .. [1] Laliberte, Marc. \"A Model for Calculating the Heat Capacity of\n Aqueous Solutions, with Updated Density and Viscosity Data.\" Journal of\n Chemical & Engineering Data 54, no. 6 (June 11, 2009): 1725-60.\n doi:10.1021/je8008123\n '''\n t = T - 273.15\n return ((c0*(1 - w_w)+c1)*exp(1E-6*(t + c4)**2))/((1 - w_w) + c2 + c3*t)", "response": "r Calculates the density of a solute in a Laliberte."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef Laliberte_density(T, ws, CASRNs):\n r'''Calculate the density of an aqueous electrolyte mixture using the form proposed by [1]_.\n Parameters are loaded by the function as needed. Units are Kelvin and Pa*s.\n\n .. math::\n \\rho_m = \\left(\\frac{w_w}{\\rho_w} + \\sum_i \\frac{w_i}{\\rho_{app_i}}\\right)^{-1}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n ws : array\n Weight fractions of fluid components other than water\n CASRNs : array\n CAS numbers of the fluid components other than water\n\n Returns\n -------\n rho_i : float\n Solution density, [kg/m^3]\n\n Notes\n -----\n Temperature range check is not used here.\n\n Examples\n --------\n >>> Laliberte_density(273.15, [0.0037838838], ['7647-14-5'])\n 1002.6250120185854\n\n References\n ----------\n .. [1] Laliberte, Marc. \"A Model for Calculating the Heat Capacity of\n Aqueous Solutions, with Updated Density and Viscosity Data.\" Journal of\n Chemical & Engineering Data 54, no. 6 (June 11, 2009): 1725-60.\n doi:10.1021/je8008123\n '''\n rho_w = Laliberte_density_w(T)\n w_w = 1 - sum(ws)\n rho = w_w/rho_w\n for i in range(len(CASRNs)):\n d = _Laliberte_Density_ParametersDict[CASRNs[i]]\n rho_i = Laliberte_density_i(T, w_w, d[\"C0\"], d[\"C1\"], d[\"C2\"], d[\"C3\"], d[\"C4\"])\n rho = rho + ws[i]/rho_i\n return 1./rho", "response": "r Calculates the density of an aqueous electrolyte mixture using the form proposed by [ 1 ]."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef Laliberte_heat_capacity_i(T, w_w, a1, a2, a3, a4, a5, a6):\n r'''Calculate the heat capacity of a solute using the form proposed by [1]_\n Parameters are needed, and a temperature, and water fraction.\n\n .. math::\n Cp_i = a_1 e^\\alpha + a_5(1-w_w)^{a_6}\n \\alpha = a_2 t + a_3 \\exp(0.01t) + a_4(1-w_w)\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n w_w : float\n Weight fraction of water in the solution\n a1-a6 : floats\n Function fit parameters\n\n Returns\n -------\n Cp_i : float\n Solute partial heat capacity, [J/kg/K]\n\n Notes\n -----\n Units are Kelvin and J/kg/K.\n Temperature range check is TODO\n\n Examples\n --------\n >>> d = _Laliberte_Heat_Capacity_ParametersDict['7647-14-5']\n >>> Laliberte_heat_capacity_i(1.5+273.15, 1-0.00398447, d[\"A1\"], d[\"A2\"], d[\"A3\"], d[\"A4\"], d[\"A5\"], d[\"A6\"])\n -2930.7353945880477\n\n References\n ----------\n .. [1] Laliberte, Marc. \"A Model for Calculating the Heat Capacity of\n Aqueous Solutions, with Updated Density and Viscosity Data.\" Journal of\n Chemical & Engineering Data 54, no. 6 (June 11, 2009): 1725-60.\n doi:10.1021/je8008123\n '''\n t = T - 273.15\n alpha = a2*t + a3*exp(0.01*t) + a4*(1. - w_w)\n Cp_i = a1*exp(alpha) + a5*(1. - w_w)**a6\n return Cp_i*1000.", "response": "r Calculates the heat capacity of a solute using the form proposed by [ 1 ] _Laliberte_Heat_Capacity_ParametersDict."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef dilute_ionic_conductivity(ionic_conductivities, zs, rhom):\n r'''This function handles the calculation of the electrical conductivity of \n a dilute electrolytic aqueous solution. Requires the mole fractions of \n each ion, the molar density of the whole mixture, and ionic conductivity \n coefficients for each ion.\n \n .. math::\n \\lambda = \\sum_i \\lambda_i^\\circ z_i \\rho_m\n \n Parameters\n ----------\n ionic_conductivities : list[float]\n Ionic conductivity coefficients of each ion in the mixture [m^2*S/mol]\n zs : list[float]\n Mole fractions of each ion in the mixture, [-]\n rhom : float\n Overall molar density of the solution, [mol/m^3]\n\n Returns\n -------\n kappa : float\n Electrical conductivity of the fluid, [S/m]\n\n Notes\n -----\n The ionic conductivity coefficients should not be `equivalent` coefficients; \n for example, 0.0053 m^2*S/mol is the equivalent conductivity coefficient of\n Mg+2, but this method expects twice its value - 0.0106. Both are reported\n commonly in literature.\n \n Water can be included in this caclulation by specifying a coefficient of\n 0. The conductivity of any electrolyte eclipses its own conductivity by \n many orders of magnitude. Any other solvents present will affect the\n conductivity extensively and there are few good methods to predict this \n effect.\n\n Examples\n --------\n Complex mixture of electrolytes ['Cl-', 'HCO3-', 'SO4-2', 'Na+', 'K+', \n 'Ca+2', 'Mg+2']:\n \n >>> ionic_conductivities = [0.00764, 0.00445, 0.016, 0.00501, 0.00735, 0.0119, 0.01061]\n >>> zs = [0.03104, 0.00039, 0.00022, 0.02413, 0.0009, 0.0024, 0.00103]\n >>> dilute_ionic_conductivity(ionic_conductivities=ionic_conductivities, zs=zs, rhom=53865.9)\n 22.05246783663\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n '''\n return sum([ci*(zi*rhom) for zi, ci in zip(zs, ionic_conductivities)])", "response": "r Returns the ionic conductivity of a dilute electrolytic aqueous solution."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef conductivity_McCleskey(T, M, lambda_coeffs, A_coeffs, B, multiplier, rho=1000.):\n r'''This function handles the calculation of the electrical conductivity of \n an electrolytic aqueous solution with one electrolyte in solution. It\n handles temperature dependency and concentrated solutions. Requires the \n temperature of the solution; its molality, and four sets of coefficients\n `lambda_coeffs`, `A_coeffs`, `B`, and `multiplier`.\n \n .. math::\n \\Lambda = \\frac{\\kappa}{C}\n \n \\Lambda = \\Lambda^0(t) - A(t) \\frac{m^{1/2}}{1+Bm^{1/2}}\n \n \\Lambda^\\circ(t) = c_1 t^2 + c_2 t + c_3\n \n A(t) = d_1 t^2 + d_2 t + d_3\n \n In the above equations, `t` is temperature in degrees Celcius;\n `m` is molality in mol/kg, and C is the concentration of the elctrolytes\n in mol/m^3, calculated as the product of density and molality.\n \n Parameters\n ----------\n T : float\n Temperature of the solution, [K]\n M : float\n Molality of the solution with respect to one electrolyte\n (mol solute / kg solvent), [mol/kg]\n lambda_coeffs : list[float]\n List of coefficients for the polynomial used to calculate `lambda`;\n length-3 coefficients provided in [1]_, [-]\n A_coeffs : list[float]\n List of coefficients for the polynomial used to calculate `A`;\n length-3 coefficients provided in [1]_, [-]\n B : float\n Empirical constant for an electrolyte, [-]\n multiplier : float\n The multiplier to obtain the absolute conductivity from the equivalent\n conductivity; ex 2 for CaCl2, [-]\n rho : float, optional\n The mass density of the aqueous mixture, [kg/m^3]\n\n Returns\n -------\n kappa : float\n Electrical conductivity of the solution at the specified molality and \n temperature [S/m]\n\n Notes\n -----\n Coefficients provided in [1]_ result in conductivity being calculated in\n units of mS/cm; they are converted to S/m before returned.\n\n Examples\n --------\n A 0.5 wt% solution of CaCl2, conductivity calculated in mS/cm\n \n >>> conductivity_McCleskey(T=293.15, M=0.045053, A_coeffs=[.03918, 3.905, \n ... 137.7], lambda_coeffs=[0.01124, 2.224, 72.36], B=3.8, multiplier=2)\n 0.8482584585108555\n\n References\n ----------\n .. [1] McCleskey, R. Blaine. \"Electrical Conductivity of Electrolytes Found\n In Natural Waters from (5 to 90) \u00b0C.\" Journal of Chemical & Engineering \n Data 56, no. 2 (February 10, 2011): 317-27. doi:10.1021/je101012n.\n '''\n t = T - 273.15\n lambda_coeff = horner(lambda_coeffs, t)\n A = horner(A_coeffs, t)\n M_root = M**0.5\n param = lambda_coeff - A*M_root/(1. + B*M_root)\n C = M*rho/1000. # convert to mol/L to get concentration\n return param*C*multiplier*0.1", "response": "r Returns the electrical conductivity of a given entry in the order in which the electrolyte is in the same species as the one in the solution."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef conductivity(CASRN=None, AvailableMethods=False, Method=None, full_info=True):\n r'''This function handles the retrieval of a chemical's conductivity.\n Lookup is based on CASRNs. Will automatically select a data source to use\n if no Method is provided; returns None if the data is not available.\n\n Function has data for approximately 100 chemicals.\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n kappa : float\n Electrical conductivity of the fluid, [S/m]\n T : float, only returned if full_info == True\n Temperature at which conductivity measurement was made\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain RI with the given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n A string for the method name to use, as defined by constants in\n conductivity_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n conductivity for the desired chemical, and will return methods instead\n of conductivity\n full_info : bool, optional\n If True, function will return the temperature at which the conductivity\n reading was made\n\n Notes\n -----\n Only one source is available in this function. It is:\n\n * 'LANGE_COND' which is from Lange's Handbook, Table 8.34 Electrical \n Conductivity of Various Pure Liquids', a compillation of data in [1]_.\n\n Examples\n --------\n >>> conductivity('7732-18-5')\n (4e-06, 291.15)\n\n References\n ----------\n .. [1] Speight, James. Lange's Handbook of Chemistry. 16 edition.\n McGraw-Hill Professional, 2005.\n '''\n def list_methods():\n methods = []\n if CASRN in Lange_cond_pure.index:\n methods.append(LANGE_COND)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n if Method == LANGE_COND:\n kappa = float(Lange_cond_pure.at[CASRN, 'Conductivity'])\n if full_info:\n T = float(Lange_cond_pure.at[CASRN, 'T'])\n\n elif Method == NONE:\n kappa, T = None, None\n else:\n raise Exception('Failure in in function')\n\n if full_info:\n return kappa, T\n else:\n return kappa", "response": "r Returns the conductivity of a given chemical."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef thermal_conductivity_Magomedov(T, P, ws, CASRNs, k_w=None):\n r'''Calculate the thermal conductivity of an aqueous mixture of\n electrolytes using the form proposed by Magomedov [1]_.\n Parameters are loaded by the function as needed. Function will fail if an\n electrolyte is not in the database.\n\n .. math::\n \\lambda = \\lambda_w\\left[ 1 - \\sum_{i=1}^n A_i (w_i + 2\\times10^{-4}\n w_i^3)\\right] - 2\\times10^{-8} PT\\sum_{i=1}^n w_i\n\n Parameters\n ----------\n T : float\n Temperature of liquid [K]\n P : float\n Pressure of the liquid [Pa]\n ws : array\n Weight fractions of liquid components other than water\n CASRNs : array\n CAS numbers of the liquid components other than water\n k_w : float\n Liquid thermal condiuctivity or pure water at T and P, [W/m/K]\n\n Returns\n -------\n kl : float\n Liquid thermal condiuctivity, [W/m/K]\n\n Notes\n -----\n Range from 273 K to 473 K, P from 0.1 MPa to 100 MPa. C from 0 to 25 mass%.\n Internal untis are MPa for pressure and weight percent.\n\n An example is sought for this function. It is not possible to reproduce\n the author's values consistently.\n\n Examples\n --------\n >>> thermal_conductivity_Magomedov(293., 1E6, [.25], ['7758-94-3'], k_w=0.59827)\n 0.548654049375\n\n References\n ----------\n .. [1] Magomedov, U. B. \"The Thermal Conductivity of Binary and\n Multicomponent Aqueous Solutions of Inorganic Substances at High\n Parameters of State.\" High Temperature 39, no. 2 (March 1, 2001):\n 221-26. doi:10.1023/A:1017518731726.\n '''\n P = P/1E6\n ws = [i*100 for i in ws]\n if not k_w:\n raise Exception('k_w correlation must be provided')\n\n sum1 = 0\n for i, CASRN in enumerate(CASRNs):\n Ai = float(Magomedovk_thermal_cond.at[CASRN, 'Ai'])\n sum1 += Ai*(ws[i] + 2E-4*ws[i]**3)\n return k_w*(1 - sum1) - 2E-8*P*T*sum(ws)", "response": "r Calculates the thermal conductivity of an aqueous mixture of an anonymized liquid components other than water at T and P."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef ionic_strength(mis, zis):\n r'''Calculate the ionic strength of a solution in one of two ways,\n depending on the inputs only. For Pitzer and Bromley models,\n `mis` should be molalities of each component. For eNRTL models,\n `mis` should be mole fractions of each electrolyte in the solution.\n This will sum to be much less than 1.\n\n .. math::\n I = \\frac{1}{2} \\sum M_i z_i^2\n\n I = \\frac{1}{2} \\sum x_i z_i^2\n\n Parameters\n ----------\n mis : list\n Molalities of each ion, or mole fractions of each ion [mol/kg or -]\n zis : list\n Charges of each ion [-]\n\n Returns\n -------\n I : float\n ionic strength, [?]\n\n Examples\n --------\n >>> ionic_strength([0.1393, 0.1393], [1, -1])\n 0.1393\n\n References\n ----------\n .. [1] Chen, Chau-Chyun, H. I. Britt, J. F. Boston, and L. B. Evans. \"Local\n Composition Model for Excess Gibbs Energy of Electrolyte Systems.\n Part I: Single Solvent, Single Completely Dissociated Electrolyte\n Systems.\" AIChE Journal 28, no. 4 (July 1, 1982): 588-96.\n doi:10.1002/aic.690280410\n .. [2] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n Weinheim, Germany: Wiley-VCH, 2012.\n '''\n return 0.5*sum([mi*zi*zi for mi, zi in zip(mis, zis)])", "response": "r Calculates the ionic strength of a single - system problem in one of two ways."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef Kweq_1981(T, rho_w):\n r'''Calculates equilibrium constant for OH- and H+ in water, according to\n [1]_. Second most recent formulation.\n\n .. math::\n \\log_{10} K_w= A + B/T + C/T^2 + D/T^3 + (E+F/T+G/T^2)\\log_{10} \\rho_w\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n rho_w : float\n Density of water, [kg/m^3]\n\n Returns\n -------\n Kweq : float\n Ionization constant of water, [-]\n\n Notes\n -----\n Density is internally converted to units of g/cm^3.\n\n A = -4.098;\n B = -3245.2;\n C = 2.2362E5;\n D = -3.984E7;\n E = 13.957;\n F = -1262.3;\n G = 8.5641E5\n\n Examples\n --------\n >>> -1*log10(Kweq_1981(600, 700))\n 11.274522047458206\n \n References\n ----------\n .. [1] Marshall, William L., and E. U. Franck. \"Ion Product of Water\n Substance, 0-1000 degree C, 1010,000 Bars New International Formulation\n and Its Background.\" Journal of Physical and Chemical Reference Data 10,\n no. 2 (April 1, 1981): 295-304. doi:10.1063/1.555643.\n '''\n rho_w = rho_w/1000.\n A = -4.098\n B = -3245.2\n C = 2.2362E5\n D = -3.984E7\n E = 13.957\n F = -1262.3\n G = 8.5641E5\n return 10**(A + B/T + C/T**2 + D/T**3 + (E + F/T + G/T**2)*log10(rho_w))", "response": "r Returns the Kweq constant for OH - and H + in water."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Kweq_IAPWS_gas(T):\n r'''Calculates equilibrium constant for OH- and H+ in water vapor,\n according to [1]_.\n This is the most recent formulation available.\n\n .. math::\n -log_{10} K_w^G = \\gamma_0 + \\gamma_1 T^{-1} + \\gamma_2 T^{-2} + \\gamma_3 T^{-3}\n\n Parameters\n ----------\n T : float\n Temperature of H2O [K]\n\n Returns\n -------\n K_w_G : float\n\n Notes\n -----\n gamma0 = 6.141500E-1; \n gamma1 = 4.825133E4; \n gamma2 = -6.770793E4; \n gamma3 = 1.010210E7\n\n Examples\n --------\n >>> Kweq_IAPWS_gas(800)\n 1.4379721554798815e-61\n \n References\n ----------\n .. [1] Bandura, Andrei V., and Serguei N. Lvov. \"The Ionization Constant\n of Water over Wide Ranges of Temperature and Density.\" Journal of Physical\n and Chemical Reference Data 35, no. 1 (March 1, 2006): 15-30.\n doi:10.1063/1.1928231\n '''\n gamma0 = 6.141500E-1\n gamma1 = 4.825133E4\n gamma2 = -6.770793E4\n gamma3 = 1.010210E7\n K_w_G = 10**(-1*(gamma0 + gamma1/T + gamma2/T**2 + gamma3/T**3))\n return K_w_G", "response": "rCalculates equilibrium constant for OH - and H + in water vapor."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef calculate(self, T, method):\n r'''Method to calculate permittivity of a liquid at temperature `T`\n with a given method.\n\n This method has no exception handling; see `T_dependent_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate relative permittivity, [K]\n method : str\n Name of the method to use\n\n Returns\n -------\n epsilon : float\n Relative permittivity of the liquid at T, [-]\n '''\n if method == CRC:\n A, B, C, D = self.CRC_coeffs\n epsilon = A + B*T + C*T**2 + D*T**3\n elif method == CRC_CONSTANT:\n epsilon = self.CRC_permittivity\n elif method in self.tabular_data:\n epsilon = self.interpolate(T, method)\n return epsilon", "response": "r Method to calculate relative permittivity of a liquid at temperature T with a given method."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncalculating the heat of combustion in J / mol.", "response": "def Hcombustion(atoms, Hf=None, HfH2O=-285825, HfCO2=-393474,\n HfSO2=-296800, HfBr2=30880, HfI2=62417, HfHCl=-92173,\n HfHF=-272711, HfP4O10=-3009940, HfO2=0, HfN2=0):\n '''Calculates the heat of combustion, in J/mol.\n Value non-hydrocarbons is not correct, but still calculable.\n\n Parameters\n ----------\n atoms : dict\n Dictionary of atoms and their counts, []\n Hf : float\n Heat of formation of given chemical, [J/mol]\n HfH2O : float, optional\n Heat of formation of water, [J/mol]\n HfCO2 : float, optional\n Heat of formation of carbon dioxide, [J/mol]\n HfSO2 : float, optional\n Heat of formation of sulfur dioxide, [J/mol]\n HfBr2 : float, optional\n Heat of formation of bromine, [J/mol]\n HfI2 : float, optional\n Heat of formation of iodine, [J/mol]\n HfHCl : float, optional\n Heat of formation of chlorine, [J/mol]\n HfHF : float, optional\n Heat of formation of hydrogen fluoride, [J/mol]\n HfP4O10 : float, optional\n Heat of formation of phosphorus pentoxide, [J/mol]\n HfO2 : float, optional\n Heat of formation of oxygen, [J/mol]\n HfN2 : float, optional\n Heat of formation of nitrogen, [J/mol]\n\n Returns\n -------\n Hc : float\n Heat of combustion of chemical, [J/mol]\n\n Notes\n -----\n Default heats of formation for chemicals are at 298 K, 1 atm.\n\n Examples\n --------\n Liquid methanol burning\n\n >>> Hcombustion({'H': 4, 'C': 1, 'O': 1}, Hf=-239100)\n -726024.0\n '''\n if not Hf or not atoms:\n return None\n nC, nH, nN, nO, nS, nBr, nI, nCl, nF, nP = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n\n if 'C' in atoms and atoms['C'] != 0:\n nC = atoms['C']\n else:\n return None # C is necessary for this formula\n if 'H' in atoms:\n nH = atoms['H']\n if 'N' in atoms:\n nN = atoms['N']\n if 'O' in atoms:\n nO = atoms['O']\n if 'S' in atoms:\n nS = atoms['S']\n if 'Br' in atoms:\n nBr = atoms['Br']\n if 'I' in atoms:\n nI = atoms['I']\n if 'Cl' in atoms:\n nCl = atoms['Cl']\n if 'F' in atoms:\n nF = atoms['F']\n if 'P' in atoms:\n nP = atoms['P']\n\n nO2_req = nC + nS + nH/4. + 5*nP/4. - (nCl + nF)/4. - nO/2.\n nCO2 = nC\n nBr2 = nBr/2.\n nI2 = nI/2.\n\n nHCl = nCl\n nHF = nF\n\n nSO2 = nS\n\n nN2 = nN/2.\n nP4O10 = nP/4.\n nH2O = (nH - nCl - nF)/2.\n\n Hc = (nBr2*HfBr2 + nI2*HfI2) + (nHCl*HfHCl + nHF*HfHF) + nSO2*HfSO2 + \\\n nN2*HfN2 + nP4O10*HfP4O10 + nH2O*HfH2O - nO2_req*HfO2 + nCO2*HfCO2 - Hf\n return Hc"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef REFPROP(T, Tc, sigma0, n0, sigma1=0, n1=0, sigma2=0, n2=0):\n r'''Calculates air-liquid surface tension using the REFPROP [1]_\n regression-based method. Relatively recent, and most accurate.\n\n .. math::\n \\sigma(T)=\\sigma_0\\left(1-\\frac{T}{T_c}\\right)^{n_0}+\n \\sigma_1\\left(1-\\frac{T}{T_c}\\right)^{n_1}+\n \\sigma_2\\left(1-\\frac{T}{T_c}\\right)^{n_2}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n sigma0 : float\n First emperical coefficient of a fluid\n n0 : float\n First emperical exponent of a fluid\n sigma1 : float, optional\n Second emperical coefficient of a fluid.\n n1 : float, optional\n Second emperical exponent of a fluid.\n sigma1 : float, optional\n Third emperical coefficient of a fluid.\n n2 : float, optional\n Third emperical exponent of a fluid.\n\n Returns\n -------\n sigma : float\n Liquid surface tension, N/m\n\n Notes\n -----\n Function as implemented in [1]_. No example necessary; results match\n literature values perfectly.\n Form of function returns imaginary results when T > Tc; None is returned\n if this is the case.\n\n\n Examples\n --------\n Parameters for water at 298.15 K\n\n >>> REFPROP(298.15, 647.096, -0.1306, 2.471, 0.2151, 1.233)\n 0.07205503890847453\n\n References\n ----------\n .. [1] Diky, Vladimir, Robert D. Chirico, Chris D. Muzny, Andrei F.\n Kazakov, Kenneth Kroenlein, Joseph W. Magee, Ilmutdin Abdulagatov, and\n Michael Frenkel. \"ThermoData Engine (TDE): Software Implementation of\n the Dynamic Data Evaluation Concept.\" Journal of Chemical Information\n and Modeling 53, no. 12 (2013): 3418-30. doi:10.1021/ci4005699.\n '''\n Tr = T/Tc\n sigma = sigma0*(1.-Tr)**n0 + sigma1*(1.-Tr)**n1 + sigma2*(1.-Tr)**n2\n return sigma", "response": "r Regression of REFPROP for a given temperature and critical temperature."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Pitzer(T, Tc, Pc, omega):\n r'''Calculates air-water surface tension using the correlation derived\n by [1]_ from the works of [2]_ and [3]_. Based on critical property CSP\n methods.\n\n .. math::\n \\sigma = P_c^{2/3}T_c^{1/3}\\frac{1.86 + 1.18\\omega}{19.05}\n \\left[ \\frac{3.75 + 0.91 \\omega}{0.291 - 0.08 \\omega}\\right]^{2/3} (1-T_r)^{11/9}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n omega : float\n Acentric factor for fluid, [-]\n\n Returns\n -------\n sigma : float\n Liquid surface tension, N/m\n\n Notes\n -----\n The source of this equation has not been reviewed.\n Internal units of presure are bar, surface tension of mN/m.\n\n Examples\n --------\n Chlorobenzene from Poling, as compared with a % error value at 293 K.\n\n >>> Pitzer(293., 633.0, 4530000.0, 0.249)\n 0.03458453513446387\n\n References\n ----------\n .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n .. [2] Curl, R. F., and Kenneth Pitzer. \"Volumetric and Thermodynamic\n Properties of Fluids-Enthalpy, Free Energy, and Entropy.\" Industrial &\n Engineering Chemistry 50, no. 2 (February 1, 1958): 265-74.\n doi:10.1021/ie50578a047\n .. [3] Pitzer, K. S.: Thermodynamics, 3d ed., New York, McGraw-Hill,\n 1995, p. 521.\n '''\n Tr = T/Tc\n Pc = Pc/1E5 # Convert to bar\n sigma = Pc**(2/3.0)*Tc**(1/3.0)*(1.86+1.18*omega)/19.05 * (\n (3.75+0.91*omega)/(0.291-0.08*omega))**(2/3.0)*(1-Tr)**(11/9.0)\n sigma = sigma/1000 # N/m, please\n return sigma", "response": "r Returns a formula that calculates air - water surface tension using the correlation derived\n by Pitzer."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef Sastri_Rao(T, Tb, Tc, Pc, chemicaltype=None):\n r'''Calculates air-water surface tension using the correlation derived by\n [1]_ based on critical property CSP methods and chemical classes.\n\n .. math::\n \\sigma = K P_c^xT_b^y T_c^z\\left[\\frac{1-T_r}{1-T_{br}}\\right]^m\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tb : float\n Boiling temperature of the fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n\n Returns\n -------\n sigma : float\n Liquid surface tension, N/m\n\n Notes\n -----\n The source of this equation has not been reviewed.\n Internal units of presure are bar, surface tension of mN/m.\n\n Examples\n --------\n Chlorobenzene from Poling, as compared with a % error value at 293 K.\n\n >>> Sastri_Rao(293.15, 404.75, 633.0, 4530000.0)\n 0.03234567739694441\n\n References\n ----------\n .. [1] Sastri, S. R. S., and K. K. Rao. \"A Simple Method to Predict\n Surface Tension of Organic Liquids.\" The Chemical Engineering Journal\n and the Biochemical Engineering Journal 59, no. 2 (October 1995): 181-86.\n doi:10.1016/0923-0467(94)02946-6.\n '''\n if chemicaltype == 'alcohol':\n k, x, y, z, m = 2.28, 0.25, 0.175, 0, 0.8\n elif chemicaltype == 'acid':\n k, x, y, z, m = 0.125, 0.50, -1.5, 1.85, 11/9.0\n else:\n k, x, y, z, m = 0.158, 0.50, -1.5, 1.85, 11/9.0\n Tr = T/Tc\n Tbr = Tb/Tc\n Pc = Pc/1E5 # Convert to bar\n sigma = k*Pc**x*Tb**y*Tc**z*((1 - Tr)/(1 - Tbr))**m\n sigma = sigma/1000 # N/m\n return sigma", "response": "r A simple method to predict air - water surface tension of the system."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Hakim_Steinberg_Stiel(T, Tc, Pc, omega, StielPolar=0):\n r'''Calculates air-water surface tension using the reference fluids methods\n of [1]_.\n\n .. math::\n \\sigma = 4.60104\\times 10^{-7} P_c^{2/3}T_c^{1/3}Q_p \\left(\\frac{1-T_r}{0.4}\\right)^m\n\n Q_p = 0.1574+0.359\\omega-1.769\\chi-13.69\\chi^2-0.51\\omega^2+1.298\\omega\\chi\n\n m = 1.21+0.5385\\omega-14.61\\chi-32.07\\chi^2-1.65\\omega^2+22.03\\omega\\chi\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n omega : float\n Acentric factor for fluid, [-]\n StielPolar : float, optional\n Stiel Polar Factor, [-]\n\n Returns\n -------\n sigma : float\n Liquid surface tension, N/m\n\n Notes\n -----\n Original equation for m and Q are used. Internal units are atm and mN/m.\n\n Examples\n --------\n 1-butanol, as compared to value in CRC Handbook of 0.02493.\n\n >>> Hakim_Steinberg_Stiel(298.15, 563.0, 4414000.0, 0.59, StielPolar=-0.07872)\n 0.021907902575190447\n\n References\n ----------\n .. [1] Hakim, D. I., David Steinberg, and L. I. Stiel. \"Generalized\n Relationship for the Surface Tension of Polar Fluids.\" Industrial &\n Engineering Chemistry Fundamentals 10, no. 1 (February 1, 1971): 174-75.\n doi:10.1021/i160037a032.\n '''\n Q = (0.1574 + 0.359*omega - 1.769*StielPolar - 13.69*StielPolar**2\n - 0.510*omega**2 + 1.298*StielPolar*omega)\n m = (1.210 + 0.5385*omega - 14.61*StielPolar - 32.07*StielPolar**2\n - 1.656*omega**2 + 22.03*StielPolar*omega)\n Tr = T/Tc\n Pc = Pc/101325.\n sigma = Pc**(2/3.)*Tc**(1/3.)*Q*((1 - Tr)/0.4)**m\n sigma = sigma/1000. # convert to N/m\n return sigma", "response": "Hakim - Steinberg - Stiel formula for the given temperature and pressure."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Mersmann_Kind_surface_tension(T, Tm, Tb, Tc, Pc, n_associated=1):\n r'''Estimates the surface tension of organic liquid substances\n according to the method of [1]_.\n\n .. math::\n \\sigma^* = \\frac{\\sigma n_{ass}^{1/3}} {(kT_c)^{1/3} T_{rm}P_c^{2/3}}\n \n \\sigma^* = \\left(\\frac{T_b - T_m}{T_m}\\right)^{1/3}\n \\left[6.25(1-T_r) + 31.3(1-T_r)^{4/3}\\right]\n \n Parameters\n ----------\n T : float\n Temperature of the fluid [K]\n Tm : float\n Melting temperature [K]\n Tb : float\n Boiling temperature of the fluid [K]\n Tc : float\n Critical temperature of the fluid [K]\n Pc : float\n Critical pressure of the fluid [Pa]\n n_associated : float\n Number of associated molecules in a cluster (2 for alcohols, 1\n otherwise), [-]\n\n Returns\n -------\n sigma : float\n Liquid-vapor surface tension [N/m]\n\n Notes\n -----\n In the equation, all quantities must be in SI units. `k` is the boltzman\n constant.\n \n Examples\n --------\n MTBE at STP (the actual value is 0.0181):\n \n >>> Mersmann_Kind_surface_tension(298.15, 164.15, 328.25, 497.1, 3430000.0)\n 0.016744309508833335\n\n References\n ----------\n .. [1] Mersmann, Alfons, and Matthias Kind. \"Prediction of Mechanical and \n Thermal Properties of Pure Liquids, of Critical Data, and of Vapor \n Pressure.\" Industrial & Engineering Chemistry Research, January 31, \n 2017. https://doi.org/10.1021/acs.iecr.6b04323.\n '''\n Tr = T/Tc\n sigma_star = ((Tb - Tm)/Tm)**(1/3.)*(6.25*(1. - Tr) + 31.3*(1. - Tr)**(4/3.))\n sigma = sigma_star*(k*Tc)**(1/3.)*(Tm/Tc)*Pc**(2/3.)*n_associated**(-1/3.)\n return sigma", "response": "Mersmann - kind surface tension of organic liquid substances."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef calculate(self, T, P, zs, ws, method):\n r'''Method to calculate surface tension of a liquid mixture at \n temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n `ws` with a given method.\n\n This method has no exception handling; see `mixture_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the property, [K]\n P : float\n Pressure at which to calculate the property, [Pa]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n method : str\n Name of the method to use\n\n Returns\n -------\n sigma : float\n Surface tension of the liquid at given conditions, [N/m]\n '''\n if method == SIMPLE:\n sigmas = [i(T) for i in self.SurfaceTensions]\n return mixing_simple(zs, sigmas)\n elif method == DIGUILIOTEJA:\n return Diguilio_Teja(T=T, xs=zs, sigmas_Tb=self.sigmas_Tb, \n Tbs=self.Tbs, Tcs=self.Tcs)\n elif method == WINTERFELDSCRIVENDAVIS:\n sigmas = [i(T) for i in self.SurfaceTensions]\n rhoms = [1./i(T, P) for i in self.VolumeLiquids]\n return Winterfeld_Scriven_Davis(zs, sigmas, rhoms)\n else:\n raise Exception('Method not valid')", "response": "r Method to calculate the surface tension of a liquid mixture at \n temperature pressure mole fractions and weight fractions of all species in the mixture at \n zs and ws."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nload group assignments from DDBST file.", "response": "def load_group_assignments_DDBST():\n '''Data is stored in the format\n InChI key\\tbool bool bool \\tsubgroup count ...\\tsubgroup count \\tsubgroup count...\n where the bools refer to whether or not the original UNIFAC, modified\n UNIFAC, and PSRK group assignments were completed correctly.\n The subgroups and their count have an indefinite length.\n '''\n # Do not allow running multiple times\n if DDBST_UNIFAC_assignments:\n return None\n with open(os.path.join(folder, 'DDBST UNIFAC assignments.tsv')) as f:\n _group_assignments = [DDBST_UNIFAC_assignments, DDBST_MODIFIED_UNIFAC_assignments, DDBST_PSRK_assignments]\n for line in f.readlines():\n key, valids, original, modified, PSRK = line.split('\\t')\n # list of whether or not each method was correctly identified or not\n valids = [True if i == '1' else False for i in valids.split(' ')]\n for groups, storage, valid in zip([original, modified, PSRK], _group_assignments, valids):\n if valid:\n groups = groups.rstrip().split(' ')\n d_data = {}\n for i in range(int(len(groups)/2)):\n d_data[int(groups[i*2])] = int(groups[i*2+1])\n storage[key] = d_data"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef UNIFAC_psi(T, subgroup1, subgroup2, subgroup_data, interaction_data, \n modified=False):\n r'''Calculates the interaction parameter psi(m, n) for two UNIFAC \n subgroups, given the system temperature, the UNIFAC subgroups considered \n for the variant of UNIFAC used, the interaction parameters for the \n variant of UNIFAC used, and whether or not the temperature dependence is \n modified from the original form, as shown below.\n\n Original temperature dependence:\n \n .. math::\n \\Psi_{mn} = \\exp\\left(\\frac{-a_{mn}}{T}\\right)\n \n Modified temperature dependence:\n \n .. math::\n \\Psi_{mn} = \\exp\\left(\\frac{-a_{mn} - b_{mn}T - c_{mn}T^2}{T}\\right)\n \n Parameters\n ----------\n T : float\n Temperature of the system, [K]\n subgroup1 : int\n First UNIFAC subgroup for identifier, [-]\n subgroup2 : int\n Second UNIFAC subgroup for identifier, [-]\n subgroup_data : dict[UNIFAC_subgroup]\n Normally provided as inputs to `UNIFAC`.\n interaction_data : dict[dict[tuple(a_mn, b_mn, c_mn)]]\n Normally provided as inputs to `UNIFAC`.\n modified : bool\n True if the modified temperature dependence is used by the interaction\n parameters, otherwise False\n\n Returns\n -------\n psi : float\n UNIFAC interaction parameter term, [-]\n\n Notes\n -----\n UNIFAC interaction parameters are asymmetric. No warning is raised if an\n interaction parameter is missing.\n\n Examples\n --------\n >>> from thermo.unifac import UFSG, UFIP, DOUFSG, DOUFIP2006\n \n >>> UNIFAC_psi(307, 18, 1, UFSG, UFIP)\n 0.9165248264184787\n \n >>> UNIFAC_psi(373.15, 9, 78, DOUFSG, DOUFIP2006, modified=True)\n 1.3703140538273264\n \n References\n ----------\n .. [1] Gmehling, Jurgen. Chemical Thermodynamics: For Process Simulation.\n Weinheim, Germany: Wiley-VCH, 2012.\n .. [2] Fredenslund, Aage, Russell L. Jones, and John M. Prausnitz. \"Group\n Contribution Estimation of Activity Coefficients in Nonideal Liquid \n Mixtures.\" AIChE Journal 21, no. 6 (November 1, 1975): 1086-99. \n doi:10.1002/aic.690210607.\n '''\n main1 = subgroup_data[subgroup1].main_group_id\n main2 = subgroup_data[subgroup2].main_group_id\n if modified:\n try:\n a, b, c = interaction_data[main1][main2]\n except:\n return 1.\n return exp((-a/T -b - c*T))\n else:\n try:\n return exp(-interaction_data[main1][main2]/T)\n except:\n return 1.", "response": "r Returns the interaction parameter psi for two subgroups."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef dipole_moment(CASRN, AvailableMethods=False, Method=None):\n r'''This function handles the retrieval of a chemical's dipole moment.\n Lookup is based on CASRNs. Will automatically select a data source to use\n if no Method is provided; returns None if the data is not available.\n\n Prefered source is 'CCCBDB'. Considerable variation in reported data has\n found.\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n dipole : float\n Dipole moment, [debye]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain dipole moment with the\n given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n The method name to use. Accepted methods are 'CCCBDB', 'MULLER', or\n 'POLING'. All valid values are also held in the list `dipole_methods`.\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n the dipole moment for the desired chemical, and will return methods\n instead of the dipole moment\n\n Notes\n -----\n A total of three sources are available for this function. They are:\n\n * 'CCCBDB', a series of critically evaluated data for compounds in\n [1]_, intended for use in predictive modeling.\n * 'MULLER', a collection of data in a\n group-contribution scheme in [2]_.\n * 'POLING', in the appendix in [3].\n \n This function returns dipole moment in units of Debye. This is actually\n a non-SI unit; to convert to SI, multiply by 3.33564095198e-30 and its\n units will be in ampere*second^2 or equivalently and more commonly given,\n coulomb*second. The constant is the result of 1E-21/c, where c is the\n speed of light.\n \n Examples\n --------\n >>> dipole_moment(CASRN='64-17-5')\n 1.44\n\n References\n ----------\n .. [1] NIST Computational Chemistry Comparison and Benchmark Database\n NIST Standard Reference Database Number 101 Release 17b, September 2015,\n Editor: Russell D. Johnson III http://cccbdb.nist.gov/\n .. [2] Muller, Karsten, Liudmila Mokrushina, and Wolfgang Arlt. \"Second-\n Order Group Contribution Method for the Determination of the Dipole\n Moment.\" Journal of Chemical & Engineering Data 57, no. 4 (April 12,\n 2012): 1231-36. doi:10.1021/je2013395.\n .. [3] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n '''\n def list_methods():\n methods = []\n if CASRN in _dipole_CCDB.index and not np.isnan(_dipole_CCDB.at[CASRN, 'Dipole']):\n methods.append(CCCBDB)\n if CASRN in _dipole_Muller.index and not np.isnan(_dipole_Muller.at[CASRN, 'Dipole']):\n methods.append(MULLER)\n if CASRN in _dipole_Poling.index and not np.isnan(_dipole_Poling.at[CASRN, 'Dipole']):\n methods.append(POLING)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == CCCBDB:\n _dipole = float(_dipole_CCDB.at[CASRN, 'Dipole'])\n elif Method == MULLER:\n _dipole = float(_dipole_Muller.at[CASRN, 'Dipole'])\n elif Method == POLING:\n _dipole = float(_dipole_Poling.at[CASRN, 'Dipole'])\n elif Method == NONE:\n _dipole = None\n else:\n raise Exception('Failure in in function')\n return _dipole", "response": "r Returns the dipole moment for a given CASRN."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Zc(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=[COMBINED]):\n r'''This function handles the retrieval of a chemical's critical\n compressibility. Lookup is based on CASRNs. Will automatically select a\n data source to use if no Method is provided; returns None if the data is\n not available.\n\n Prefered sources are 'IUPAC' for organic chemicals, and 'MATTHEWS' for \n inorganic chemicals. Function has data for approximately 1000 chemicals.\n\n Examples\n --------\n >>> Zc(CASRN='64-17-5')\n 0.24100000000000002\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n Zc : float\n Critical compressibility, [-]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain Vc with the given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n The method name to use. Accepted methods are 'IUPAC', 'MATTHEWS', \n 'CRC', 'PSRK', 'YAWS', and 'COMBINED'. All valid values are also held \n in `Zc_methods`.\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n Zc for the desired chemical, and will return methods instead of Zc\n IgnoreMethods : list, optional\n A list of methods to ignore in obtaining the full list of methods,\n useful for for performance reasons and ignoring inaccurate methods\n\n Notes\n -----\n A total of five sources are available for this function. They are:\n\n * 'IUPAC', a series of critically evaluated\n experimental datum for organic compounds in [1]_, [2]_, [3]_, [4]_,\n [5]_, [6]_, [7]_, [8]_, [9]_, [10]_, [11]_, and [12]_.\n * 'MATTHEWS', a series of critically\n evaluated data for inorganic compounds in [13]_.\n * 'CRC', a compillation of critically\n evaluated data by the TRC as published in [14]_.\n * 'PSRK', a compillation of experimental and\n estimated data published in [15]_.\n * 'YAWS', a large compillation of data from a\n variety of sources; no data points are sourced in the work of [16]_.\n\n References\n ----------\n .. [1] Ambrose, Douglas, and Colin L. Young. \"Vapor-Liquid Critical\n Properties of Elements and Compounds. 1. An Introductory Survey.\"\n Journal of Chemical & Engineering Data 41, no. 1 (January 1, 1996):\n 154-154. doi:10.1021/je950378q.\n .. [2] Ambrose, Douglas, and Constantine Tsonopoulos. \"Vapor-Liquid\n Critical Properties of Elements and Compounds. 2. Normal Alkanes.\"\n Journal of Chemical & Engineering Data 40, no. 3 (May 1, 1995): 531-46.\n doi:10.1021/je00019a001.\n .. [3] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n Critical Properties of Elements and Compounds. 3. Aromatic\n Hydrocarbons.\" Journal of Chemical & Engineering Data 40, no. 3\n (May 1, 1995): 547-58. doi:10.1021/je00019a002.\n .. [4] Gude, Michael, and Amyn S. Teja. \"Vapor-Liquid Critical Properties\n of Elements and Compounds. 4. Aliphatic Alkanols.\" Journal of Chemical\n & Engineering Data 40, no. 5 (September 1, 1995): 1025-36.\n doi:10.1021/je00021a001.\n .. [5] Daubert, Thomas E. \"Vapor-Liquid Critical Properties of Elements\n and Compounds. 5. Branched Alkanes and Cycloalkanes.\" Journal of\n Chemical & Engineering Data 41, no. 3 (January 1, 1996): 365-72.\n doi:10.1021/je9501548.\n .. [6] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n Critical Properties of Elements and Compounds. 6. Unsaturated Aliphatic\n Hydrocarbons.\" Journal of Chemical & Engineering Data 41, no. 4\n (January 1, 1996): 645-56. doi:10.1021/je9501999.\n .. [7] Kudchadker, Arvind P., Douglas Ambrose, and Constantine Tsonopoulos.\n \"Vapor-Liquid Critical Properties of Elements and Compounds. 7. Oxygen\n Compounds Other Than Alkanols and Cycloalkanols.\" Journal of Chemical &\n Engineering Data 46, no. 3 (May 1, 2001): 457-79. doi:10.1021/je0001680.\n .. [8] Tsonopoulos, Constantine, and Douglas Ambrose. \"Vapor-Liquid\n Critical Properties of Elements and Compounds. 8. Organic Sulfur,\n Silicon, and Tin Compounds (C + H + S, Si, and Sn).\" Journal of Chemical\n & Engineering Data 46, no. 3 (May 1, 2001): 480-85.\n doi:10.1021/je000210r.\n .. [9] Marsh, Kenneth N., Colin L. Young, David W. Morton, Douglas Ambrose,\n and Constantine Tsonopoulos. \"Vapor-Liquid Critical Properties of\n Elements and Compounds. 9. Organic Compounds Containing Nitrogen.\"\n Journal of Chemical & Engineering Data 51, no. 2 (March 1, 2006):\n 305-14. doi:10.1021/je050221q.\n .. [10] Marsh, Kenneth N., Alan Abramson, Douglas Ambrose, David W. Morton,\n Eugene Nikitin, Constantine Tsonopoulos, and Colin L. Young.\n \"Vapor-Liquid Critical Properties of Elements and Compounds. 10. Organic\n Compounds Containing Halogens.\" Journal of Chemical & Engineering Data\n 52, no. 5 (September 1, 2007): 1509-38. doi:10.1021/je700336g.\n .. [11] Ambrose, Douglas, Constantine Tsonopoulos, and Eugene D. Nikitin.\n \"Vapor-Liquid Critical Properties of Elements and Compounds. 11. Organic\n Compounds Containing B + O; Halogens + N, + O, + O + S, + S, + Si;\n N + O; and O + S, + Si.\" Journal of Chemical & Engineering Data 54,\n no. 3 (March 12, 2009): 669-89. doi:10.1021/je800580z.\n .. [12] Ambrose, Douglas, Constantine Tsonopoulos, Eugene D. Nikitin, David\n W. Morton, and Kenneth N. Marsh. \"Vapor-Liquid Critical Properties of\n Elements and Compounds. 12. Review of Recent Data for Hydrocarbons and\n Non-Hydrocarbons.\" Journal of Chemical & Engineering Data, October 5,\n 2015, 151005081500002. doi:10.1021/acs.jced.5b00571.\n .. [13] Mathews, Joseph F. \"Critical Constants of Inorganic Substances.\"\n Chemical Reviews 72, no. 1 (February 1, 1972): 71-100.\n doi:10.1021/cr60275a004.\n .. [14] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n .. [15] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n Comprehensive Revision and Extension IV, Including Critical Constants\n and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n 227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n .. [16] Yaws, Carl L. Thermophysical Properties of Chemicals and\n Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n Publishing, 2014.\n '''\n def list_methods():\n methods = []\n if CASRN in _crit_IUPAC.index and not np.isnan(_crit_IUPAC.at[CASRN, 'Zc']):\n methods.append(IUPAC)\n if CASRN in _crit_Matthews.index and not np.isnan(_crit_Matthews.at[CASRN, 'Zc']):\n methods.append(MATTHEWS)\n if CASRN in _crit_CRC.index and not np.isnan(_crit_CRC.at[CASRN, 'Zc']):\n methods.append(CRC)\n if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'Zc']):\n methods.append(PSRK)\n if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'Zc']):\n methods.append(YAWS)\n if Tc(CASRN) and Vc(CASRN) and Pc(CASRN):\n methods.append(COMBINED)\n if IgnoreMethods:\n for Method in IgnoreMethods:\n if Method in methods:\n methods.remove(Method)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n if Method == IUPAC:\n _Zc = float(_crit_IUPAC.at[CASRN, 'Zc'])\n elif Method == PSRK:\n _Zc = float(_crit_PSRKR4.at[CASRN, 'Zc'])\n elif Method == MATTHEWS:\n _Zc = float(_crit_Matthews.at[CASRN, 'Zc'])\n elif Method == CRC:\n _Zc = float(_crit_CRC.at[CASRN, 'Zc'])\n elif Method == YAWS:\n _Zc = float(_crit_Yaws.at[CASRN, 'Zc'])\n elif Method == COMBINED:\n _Zc = Vc(CASRN)*Pc(CASRN)/Tc(CASRN)/R\n elif Method == NONE:\n return None\n else:\n raise Exception('Failure in in function')\n return _Zc", "response": "r Returns a new critical compressibility tree for the given CASRN."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Ihmels(Tc=None, Pc=None, Vc=None):\n r'''Most recent, and most recommended method of estimating critical\n properties from each other. Two of the three properties are required.\n This model uses the \"critical surface\", a general plot of Tc vs Pc vs Vc.\n The model used 421 organic compounds to derive equation.\n The general equation is in [1]_:\n\n .. math::\n P_c = -0.025 + 2.215 \\frac{T_c}{V_c}\n\n Parameters\n ----------\n Tc : float\n Critical temperature of fluid (optional) [K]\n Pc : float\n Critical pressure of fluid (optional) [Pa]\n Vc : float\n Critical volume of fluid (optional) [m^3/mol]\n\n Returns\n -------\n Tc, Pc or Vc : float\n Critical property of fluid [K], [Pa], or [m^3/mol]\n\n Notes\n -----\n The prediction of Tc from Pc and Vc is not tested, as this is not necessary\n anywhere, but it is implemented.\n Internal units are MPa, cm^3/mol, and K. A slight error occurs when\n Pa, cm^3/mol and K are used instead, on the order of <0.2%.\n Their equation was also compared with 56 inorganic and elements.\n Devations of 20% for <200K or >1000K points.\n\n Examples\n --------a\n Succinic acid [110-15-6]\n\n >>> Ihmels(Tc=851.0, Vc=0.000308)\n 6095016.233766234\n\n References\n ----------\n .. [1] Ihmels, E. Christian. \"The Critical Surface.\" Journal of Chemical\n & Engineering Data 55, no. 9 (September 9, 2010): 3474-80.\n doi:10.1021/je100167w.\n '''\n if Tc and Vc:\n Vc = Vc*1E6 # m^3/mol to cm^3/mol\n Pc = -0.025+2.215*Tc/Vc\n Pc = Pc*1E6 # MPa to Pa\n return Pc\n elif Tc and Pc:\n Pc = Pc/1E6 # Pa to MPa\n Vc = 443*Tc/(200*Pc+5)\n Vc = Vc/1E6 # cm^3/mol to m^3/mol\n return Vc\n elif Pc and Vc:\n Pc = Pc/1E6 # Pa to MPa\n Vc = Vc*1E6 # m^3/mol to cm^3/mol\n Tc = 5.0/443*(40*Pc*Vc + Vc)\n return Tc\n else:\n raise Exception('Two of Tc, Pc, and Vc must be provided')", "response": "r Estimates critical properties from each other."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Meissner(Tc=None, Pc=None, Vc=None):\n r'''Old (1942) relationship for estimating critical\n properties from each other. Two of the three properties are required.\n This model uses the \"critical surface\", a general plot of Tc vs Pc vs Vc.\n The model used 42 organic and inorganic compounds to derive the equation.\n The general equation is in [1]_:\n\n .. math::\n P_c = \\frac{2.08 T_c}{V_c-8}\n\n Parameters\n ----------\n Tc : float, optional\n Critical temperature of fluid [K]\n Pc : float, optional\n Critical pressure of fluid [Pa]\n Vc : float, optional\n Critical volume of fluid [m^3/mol]\n\n Returns\n -------\n Tc, Pc or Vc : float\n Critical property of fluid [K], [Pa], or [m^3/mol]\n\n Notes\n -----\n The prediction of Tc from Pc and Vc is not tested, as this is not necessary\n anywhere, but it is implemented.\n Internal units are atm, cm^3/mol, and K. A slight error occurs when\n Pa, cm^3/mol and K are used instead, on the order of <0.2%.\n This equation is less accurate than that of Ihmels, but surprisingly close.\n The author also proposed means of estimated properties independently.\n\n Examples\n --------\n Succinic acid [110-15-6]\n\n >>> Meissner(Tc=851.0, Vc=0.000308)\n 5978445.199999999\n\n References\n ----------\n .. [1] Meissner, H. P., and E. M. Redding. \"Prediction of Critical\n Constants.\" Industrial & Engineering Chemistry 34, no. 5\n (May 1, 1942): 521-26. doi:10.1021/ie50389a003.\n '''\n if Tc and Vc:\n Vc = Vc*1E6\n Pc = 20.8*Tc/(Vc-8)\n Pc = 101325*Pc # atm to Pa\n return Pc\n elif Tc and Pc:\n Pc = Pc/101325. # Pa to atm\n Vc = 104/5.0*Tc/Pc+8\n Vc = Vc/1E6 # cm^3/mol to m^3/mol\n return Vc\n elif Pc and Vc:\n Pc = Pc/101325. # Pa to atm\n Vc = Vc*1E6 # m^3/mol to cm^3/mol\n Tc = 5./104.0*Pc*(Vc-8)\n return Tc\n else:\n raise Exception('Two of Tc, Pc, and Vc must be provided')", "response": "r Estimates the critical properties of a resource in a Meissner model."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef critical_surface(Tc=None, Pc=None, Vc=None, AvailableMethods=False,\n Method=None):\n r'''Function for calculating a critical property of a substance from its\n other two critical properties. Calls functions Ihmels, Meissner, and\n Grigoras, each of which use a general 'Critical surface' type of equation.\n Limited accuracy is expected due to very limited theoretical backing.\n\n Parameters\n ----------\n Tc : float\n Critical temperature of fluid (optional) [K]\n Pc : float\n Critical pressure of fluid (optional) [Pa]\n Vc : float\n Critical volume of fluid (optional) [m^3/mol]\n AvailableMethods : bool\n Request available methods for given parameters\n Method : string\n Request calculation uses the requested method\n\n Returns\n -------\n Tc, Pc or Vc : float\n Critical property of fluid [K], [Pa], or [m^3/mol]\n\n Notes\n -----\n\n Examples\n --------\n Decamethyltetrasiloxane [141-62-8]\n\n >>> critical_surface(Tc=599.4, Pc=1.19E6, Method='IHMELS')\n 0.0010927333333333334\n '''\n def list_methods():\n methods = []\n if (Tc and Pc) or (Tc and Vc) or (Pc and Vc):\n methods.append(IHMELS)\n methods.append(MEISSNER)\n methods.append(GRIGORAS)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n if Method == IHMELS:\n Third = Ihmels(Tc=Tc, Pc=Pc, Vc=Vc)\n elif Method == MEISSNER:\n Third = Meissner(Tc=Tc, Pc=Pc, Vc=Vc)\n elif Method == GRIGORAS:\n Third = Grigoras(Tc=Tc, Pc=Pc, Vc=Vc)\n elif Method == NONE:\n Third = None\n else:\n raise Exception('Failure in in function')\n return Third", "response": "r Function for calculating a critical property of a substance from its base class and other critical properties."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef Li(zs, Tcs, Vcs):\n r'''Calculates critical temperature of a mixture according to\n mixing rules in [1]_. Better than simple mixing rules.\n\n .. math::\n T_{cm} = \\sum_{i=1}^n \\Phi_i T_{ci}\\\\\n \\Phi = \\frac{x_i V_{ci}}{\\sum_{j=1}^n x_j V_{cj}}\n\n Parameters\n ----------\n zs : array-like\n Mole fractions of all components\n Tcs : array-like\n Critical temperatures of all components, [K]\n Vcs : array-like\n Critical volumes of all components, [m^3/mol]\n\n Returns\n -------\n Tcm : float\n Critical temperatures of the mixture, [K]\n\n Notes\n -----\n Reviewed in many papers on critical mixture temperature.\n\n Second example is from Najafi (2015), for ethylene, Benzene, ethylbenzene.\n This is similar to but not identical to the result from the article. The\n experimental point is 486.9 K.\n\n 2rd example is from Najafi (2015), for:\n butane/pentane/hexane 0.6449/0.2359/0.1192 mixture, exp: 450.22 K.\n Its result is identical to that calculated in the article.\n\n Examples\n --------\n Nitrogen-Argon 50/50 mixture\n\n >>> Li([0.5, 0.5], [126.2, 150.8], [8.95e-05, 7.49e-05])\n 137.40766423357667\n\n butane/pentane/hexane 0.6449/0.2359/0.1192 mixture, exp: 450.22 K.\n\n >>> Li([0.6449, 0.2359, 0.1192], [425.12, 469.7, 507.6],\n ... [0.000255, 0.000313, 0.000371])\n 449.68261498555444\n\n References\n ----------\n .. [1] Li, C. C. \"Critical Temperature Estimation for Simple Mixtures.\"\n The Canadian Journal of Chemical Engineering 49, no. 5\n (October 1, 1971): 709-10. doi:10.1002/cjce.5450490529.\n '''\n if not none_and_length_check([zs, Tcs, Vcs]):\n raise Exception('Function inputs are incorrect format')\n\n denominator = sum(zs[i]*Vcs[i] for i in range(len(zs)))\n Tcm = 0\n for i in range(len(zs)):\n Tcm += zs[i]*Vcs[i]*Tcs[i]/denominator\n return Tcm", "response": "r Returns a string that represents the critical temperature of a mixture."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncalculate critical temperature of a mixture according to Chueh - Prausnitz.", "response": "def Chueh_Prausnitz_Tc(zs, Tcs, Vcs, taus):\n r'''Calculates critical temperature of a mixture according to\n mixing rules in [1]_.\n\n .. math::\n T_{cm} = \\sum_i^n \\theta_i Tc_i + \\sum_i^n\\sum_j^n(\\theta_i \\theta_j\n \\tau_{ij})T_{ref}\n\n \\theta = \\frac{x_i V_{ci}^{2/3}}{\\sum_{j=1}^n x_j V_{cj}^{2/3}}\n\n For a binary mxiture, this simplifies to:\n\n .. math::\n T_{cm} = \\theta_1T_{c1} + \\theta_2T_{c2} + 2\\theta_1\\theta_2\\tau_{12}\n\n Parameters\n ----------\n zs : array-like\n Mole fractions of all components\n Tcs : array-like\n Critical temperatures of all components, [K]\n Vcs : array-like\n Critical volumes of all components, [m^3/mol]\n taus : array-like of shape `zs` by `zs`\n Interaction parameters\n\n Returns\n -------\n Tcm : float\n Critical temperatures of the mixture, [K]\n\n Notes\n -----\n All parameters, even if zero, must be given to this function.\n\n Examples\n --------\n butane/pentane/hexane 0.6449/0.2359/0.1192 mixture, exp: 450.22 K.\n\n >>> Chueh_Prausnitz_Tc([0.6449, 0.2359, 0.1192], [425.12, 469.7, 507.6],\n ... [0.000255, 0.000313, 0.000371], [[0, 1.92681, 6.80358],\n ... [1.92681, 0, 1.89312], [ 6.80358, 1.89312, 0]])\n 450.1225764723492\n\n References\n ----------\n .. [1] Chueh, P. L., and J. M. Prausnitz. \"Vapor-Liquid Equilibria at High\n Pressures: Calculation of Critical Temperatures, Volumes, and Pressures\n of Nonpolar Mixtures.\" AIChE Journal 13, no. 6 (November 1, 1967):\n 1107-13. doi:10.1002/aic.690130613.\n .. [2] Najafi, Hamidreza, Babak Maghbooli, and Mohammad Amin Sobati.\n \"Prediction of True Critical Temperature of Multi-Component Mixtures:\n Extending Fast Estimation Methods.\" Fluid Phase Equilibria 392\n (April 25, 2015): 104-26. doi:10.1016/j.fluid.2015.02.001.\n '''\n if not none_and_length_check([zs, Tcs, Vcs]):\n raise Exception('Function inputs are incorrect format')\n\n denominator = sum(zs[i]*Vcs[i]**(2/3.) for i in range(len(zs)))\n Tcm = 0\n for i in range(len(zs)):\n Tcm += zs[i]*Vcs[i]**(2/3.)*Tcs[i]/denominator\n for j in range(len(zs)):\n Tcm += (zs[i]*Vcs[i]**(2/3.)/denominator)*(zs[j]*Vcs[j]**(2/3.)/denominator)*taus[i][j]\n return Tcm"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef Grieves_Thodos(zs, Tcs, Aijs):\n r'''Calculates critical temperature of a mixture according to\n mixing rules in [1]_.\n\n .. math::\n T_{cm} = \\sum_{i} \\frac{T_{ci}}{1 + (1/x_i)\\sum_j A_{ij} x_j}\n\n For a binary mxiture, this simplifies to:\n\n .. math::\n T_{cm} = \\frac{T_{c1}}{1 + (x_2/x_1)A_{12}} + \\frac{T_{c2}}\n {1 + (x_1/x_2)A_{21}}\n\n Parameters\n ----------\n zs : array-like\n Mole fractions of all components\n Tcs : array-like\n Critical temperatures of all components, [K]\n Aijs : array-like of shape `zs` by `zs`\n Interaction parameters\n\n Returns\n -------\n Tcm : float\n Critical temperatures of the mixture, [K]\n\n Notes\n -----\n All parameters, even if zero, must be given to this function.\n Giving 0s gives really bad results however.\n\n Examples\n --------\n butane/pentane/hexane 0.6449/0.2359/0.1192 mixture, exp: 450.22 K.\n\n >>> Grieves_Thodos([0.6449, 0.2359, 0.1192], [425.12, 469.7, 507.6], [[0, 1.2503, 1.516], [0.799807, 0, 1.23843], [0.659633, 0.807474, 0]])\n 450.1839618758971\n\n References\n ----------\n .. [1] Grieves, Robert B., and George Thodos. \"The Critical Temperatures of\n Multicomponent Hydrocarbon Systems.\" AIChE Journal 8, no. 4\n (September 1, 1962): 550-53. doi:10.1002/aic.690080426.\n .. [2] Najafi, Hamidreza, Babak Maghbooli, and Mohammad Amin Sobati.\n \"Prediction of True Critical Temperature of Multi-Component Mixtures:\n Extending Fast Estimation Methods.\" Fluid Phase Equilibria 392\n (April 25, 2015): 104-26. doi:10.1016/j.fluid.2015.02.001.\n '''\n if not none_and_length_check([zs, Tcs]):\n raise Exception('Function inputs are incorrect format')\n Tcm = 0\n for i in range(len(zs)):\n Tcm += Tcs[i]/(1. + 1./zs[i]*sum(Aijs[i][j]*zs[j] for j in range(len(zs))))\n return Tcm", "response": "Grieves Robert B and George Thodos."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef modified_Wilson_Tc(zs, Tcs, Aijs):\n r'''Calculates critical temperature of a mixture according to\n mixing rules in [1]_. Equation\n\n .. math::\n T_{cm} = \\sum_i x_i T_{ci} + C\\sum_i x_i \\ln \\left(x_i + \\sum_j x_j A_{ij}\\right)T_{ref}\n\n For a binary mxiture, this simplifies to:\n\n .. math::\n T_{cm} = x_1 T_{c1} + x_2 T_{c2} + C[x_1 \\ln(x_1 + x_2A_{12}) + x_2\\ln(x_2 + x_1 A_{21})]\n\n Parameters\n ----------\n zs : float\n Mole fractions of all components\n Tcs : float\n Critical temperatures of all components, [K]\n Aijs : matrix\n Interaction parameters\n\n Returns\n -------\n Tcm : float\n Critical temperatures of the mixture, [K]\n\n Notes\n -----\n The equation and original article has been reviewed.\n [1]_ has 75 binary systems, and additional multicomponent mixture parameters.\n All parameters, even if zero, must be given to this function.\n\n 2rd example is from [2]_, for:\n butane/pentane/hexane 0.6449/0.2359/0.1192 mixture, exp: 450.22 K.\n Its result is identical to that calculated in the article.\n\n Examples\n --------\n >>> modified_Wilson_Tc([0.6449, 0.2359, 0.1192], [425.12, 469.7, 507.6],\n ... [[0, 1.174450, 1.274390], [0.835914, 0, 1.21038],\n ... [0.746878, 0.80677, 0]])\n 450.0305966823031\n\n References\n ----------\n .. [1] Teja, Amyn S., Kul B. Garg, and Richard L. Smith. \"A Method for the\n Calculation of Gas-Liquid Critical Temperatures and Pressures of\n Multicomponent Mixtures.\" Industrial & Engineering Chemistry Process\n Design and Development 22, no. 4 (1983): 672-76.\n .. [2] Najafi, Hamidreza, Babak Maghbooli, and Mohammad Amin Sobati.\n \"Prediction of True Critical Temperature of Multi-Component Mixtures:\n Extending Fast Estimation Methods.\" Fluid Phase Equilibria 392\n (April 25, 2015): 104-26. doi:10.1016/j.fluid.2015.02.001.\n '''\n if not none_and_length_check([zs, Tcs]):\n raise Exception('Function inputs are incorrect format')\n C = -2500\n Tcm = sum(zs[i]*Tcs[i] for i in range(len(zs)))\n for i in range(len(zs)):\n Tcm += C*zs[i]*log(zs[i] + sum(zs[j]*Aijs[i][j] for j in range(len(zs))))\n return Tcm", "response": "r Calculates the critical temperature of a mixture according to the Wilson s model."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Tc_mixture(Tcs=None, zs=None, CASRNs=None, AvailableMethods=False, Method=None): # pragma: no cover\n '''This function handles the retrival of a mixture's critical temperature.\n\n This API is considered experimental, and is expected to be removed in a\n future release in favor of a more complete object-oriented interface.\n\n >>> Tc_mixture([400, 550], [0.3, 0.7])\n 505.0\n '''\n def list_methods():\n methods = []\n if none_and_length_check([Tcs]):\n methods.append('Simple')\n methods.append('None')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n if Method == 'Simple':\n return mixing_simple(zs, Tcs)\n elif Method == 'None':\n return None\n else:\n raise Exception('Failure in in function')", "response": "This function handles the retrival of a mixture s critical temperature."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncalculating critical volume of a mixture according to Chueh - Prausnitz.", "response": "def Chueh_Prausnitz_Vc(zs, Vcs, nus):\n r'''Calculates critical volume of a mixture according to\n mixing rules in [1]_ with an interaction parameter.\n\n .. math::\n V_{cm} = \\sum_i^n \\theta_i V_{ci} + \\sum_i^n\\sum_j^n(\\theta_i \\theta_j \\nu_{ij})V_{ref}\n \\theta = \\frac{x_i V_{ci}^{2/3}}{\\sum_{j=1}^n x_j V_{cj}^{2/3}}\n\n Parameters\n ----------\n zs : float\n Mole fractions of all components\n Vcs : float\n Critical volumes of all components, [m^3/mol]\n nus : matrix\n Interaction parameters, [cm^3/mol]\n\n Returns\n -------\n Vcm : float\n Critical volume of the mixture, [m^3/mol]\n\n Notes\n -----\n All parameters, even if zero, must be given to this function.\n nu parameters are in cm^3/mol, but are converted to m^3/mol inside the function\n\n\n Examples\n --------\n 1-butanol/benzene 0.4271/0.5729 mixture, Vcm = 268.096 mL/mol.\n\n >>> Chueh_Prausnitz_Vc([0.4271, 0.5729], [0.000273, 0.000256], [[0, 5.61847], [5.61847, 0]])\n 0.00026620503424517445\n\n References\n ----------\n .. [1] Chueh, P. L., and J. M. Prausnitz. \"Vapor-Liquid Equilibria at High\n Pressures: Calculation of Critical Temperatures, Volumes, and Pressures\n of Nonpolar Mixtures.\" AIChE Journal 13, no. 6 (November 1, 1967):\n 1107-13. doi:10.1002/aic.690130613.\n .. [2] Najafi, Hamidreza, Babak Maghbooli, and Mohammad Amin Sobati.\n \"Prediction of True Critical Volume of Multi-Component Mixtures:\n Extending Fast Estimation Methods.\" Fluid Phase Equilibria 386\n (January 25, 2015): 13-29. doi:10.1016/j.fluid.2014.11.008.\n '''\n if not none_and_length_check([zs, Vcs]): # check same-length inputs\n raise Exception('Function inputs are incorrect format')\n\n denominator = sum(zs[i]*Vcs[i]**(2/3.) for i in range(len(zs)))\n Vcm = 0\n for i in range(len(zs)):\n Vcm += zs[i]*Vcs[i]**(2/3.)*Vcs[i]/denominator\n for j in range(len(zs)):\n Vcm += (zs[i]*Vcs[i]**(2/3.)/denominator)*(zs[j]*Vcs[j]**(2/3.)/denominator)*nus[i][j]/1E6\n return Vcm"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef modified_Wilson_Vc(zs, Vcs, Aijs):\n r'''Calculates critical volume of a mixture according to\n mixing rules in [1]_ with parameters. Equation\n\n .. math::\n V_{cm} = \\sum_i x_i V_{ci} + C\\sum_i x_i \\ln \\left(x_i + \\sum_j x_j A_{ij}\\right)V_{ref}\n\n For a binary mxiture, this simplifies to:\n\n .. math::\n V_{cm} = x_1 V_{c1} + x_2 V_{c2} + C[x_1 \\ln(x_1 + x_2A_{12}) + x_2\\ln(x_2 + x_1 A_{21})]\n\n Parameters\n ----------\n zs : float\n Mole fractions of all components\n Vcs : float\n Critical volumes of all components, [m^3/mol]\n Aijs : matrix\n Interaction parameters, [cm^3/mol]\n\n Returns\n -------\n Vcm : float\n Critical volume of the mixture, [m^3/mol]\n\n Notes\n -----\n The equation and original article has been reviewed.\n All parameters, even if zero, must be given to this function.\n C = -2500\n\n All parameters, even if zero, must be given to this function.\n nu parameters are in cm^3/mol, but are converted to m^3/mol inside the function\n\n\n Examples\n --------\n 1-butanol/benzene 0.4271/0.5729 mixture, Vcm = 268.096 mL/mol.\n\n >>> modified_Wilson_Vc([0.4271, 0.5729], [0.000273, 0.000256],\n ... [[0, 0.6671250], [1.3939900, 0]])\n 0.0002664335032706881\n\n References\n ----------\n .. [1] Teja, Amyn S., Kul B. Garg, and Richard L. Smith. \"A Method for the\n Calculation of Gas-Liquid Critical Temperatures and Pressures of\n Multicomponent Mixtures.\" Industrial & Engineering Chemistry Process\n Design and Development 22, no. 4 (1983): 672-76.\n .. [2] Najafi, Hamidreza, Babak Maghbooli, and Mohammad Amin Sobati.\n \"Prediction of True Critical Temperature of Multi-Component Mixtures:\n Extending Fast Estimation Methods.\" Fluid Phase Equilibria 392\n (April 25, 2015): 104-26. doi:10.1016/j.fluid.2015.02.001.\n '''\n if not none_and_length_check([zs, Vcs]): # check same-length inputs\n raise Exception('Function inputs are incorrect format')\n C = -2500\n Vcm = sum(zs[i]*Vcs[i] for i in range(len(zs)))\n for i in range(len(zs)):\n Vcm += C*zs[i]*log(zs[i] + sum(zs[j]*Aijs[i][j] for j in range(len(zs))))/1E6\n return Vcm", "response": "r Calculates the critical volume of a mixture according to the mixing rules in [ 1 ] _."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef Vc_mixture(Vcs=None, zs=None, CASRNs=None, AvailableMethods=False, Method=None): # pragma: no cover\n '''This function handles the retrival of a mixture's critical temperature.\n\n This API is considered experimental, and is expected to be removed in a\n future release in favor of a more complete object-oriented interface.\n\n >>> Vc_mixture([5.6E-5, 2E-4], [0.3, 0.7])\n 0.0001568\n '''\n def list_methods():\n methods = []\n if none_and_length_check([Vcs]):\n methods.append('Simple')\n methods.append('None')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n if Method == 'Simple':\n return mixing_simple(zs, Vcs)\n elif Method == 'None':\n return None\n else:\n raise Exception('Failure in in function')", "response": "This function handles the retrival of a mixture s critical temperature."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nlook up the CAS number of a chemical by searching and testing for the string being any of the following types of chemical identifiers: * Name, in IUPAC form or common form or a synonym registered in PubChem * InChI name, prefixed by 'InChI=1S/' or 'InChI=1/' * InChI key, prefixed by 'InChIKey=' * PubChem CID, prefixed by 'PubChem=' * SMILES (prefix with 'SMILES=' to ensure smiles parsing; ex. 'C' will return Carbon as it is an element whereas the SMILES interpretation for 'C' is methane) * CAS number (obsolete numbers may point to the current number) If the input is an ID representing an element, the following additional inputs may be specified as * Atomic symbol (ex 'Na') * Atomic number (as a string) Parameters ---------- ID : str One of the name formats described above Returns ------- CASRN : string A three-piece, dash-separated set of numbers Notes ----- An exception is raised if the name cannot be identified. The PubChem database includes a wide variety of other synonyms, but these may not be present for all chemcials. Examples -------- >>> CAS_from_any('water') '7732-18-5' >>> CAS_from_any('InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3') '64-17-5' >>> CAS_from_any('CCCCCCCCCC') '124-18-5' >>> CAS_from_any('InChIKey=LFQSCWFLJHTTHZ-UHFFFAOYSA-N') '64-17-5' >>> CAS_from_any('pubchem=702') '64-17-5' >>> CAS_from_any('O') # only elements can be specified by symbol '17778-80-2'", "response": "def CAS_from_any(ID, autoload=False):\n '''Looks up the CAS number of a chemical by searching and testing for the\n string being any of the following types of chemical identifiers:\n \n * Name, in IUPAC form or common form or a synonym registered in PubChem\n * InChI name, prefixed by 'InChI=1S/' or 'InChI=1/'\n * InChI key, prefixed by 'InChIKey='\n * PubChem CID, prefixed by 'PubChem='\n * SMILES (prefix with 'SMILES=' to ensure smiles parsing; ex.\n 'C' will return Carbon as it is an element whereas the SMILES \n interpretation for 'C' is methane)\n * CAS number (obsolete numbers may point to the current number) \n\n If the input is an ID representing an element, the following additional \n inputs may be specified as \n \n * Atomic symbol (ex 'Na')\n * Atomic number (as a string)\n\n Parameters\n ----------\n ID : str\n One of the name formats described above\n\n Returns\n -------\n CASRN : string\n A three-piece, dash-separated set of numbers\n\n Notes\n -----\n An exception is raised if the name cannot be identified. The PubChem \n database includes a wide variety of other synonyms, but these may not be\n present for all chemcials.\n\n Examples\n --------\n >>> CAS_from_any('water')\n '7732-18-5'\n >>> CAS_from_any('InChI=1S/C2H6O/c1-2-3/h3H,2H2,1H3')\n '64-17-5'\n >>> CAS_from_any('CCCCCCCCCC')\n '124-18-5'\n >>> CAS_from_any('InChIKey=LFQSCWFLJHTTHZ-UHFFFAOYSA-N')\n '64-17-5'\n >>> CAS_from_any('pubchem=702')\n '64-17-5'\n >>> CAS_from_any('O') # only elements can be specified by symbol\n '17778-80-2'\n '''\n ID = ID.strip()\n ID_lower = ID.lower()\n if ID in periodic_table:\n if periodic_table[ID].number not in homonuclear_elemental_gases:\n return periodic_table[ID].CAS\n else:\n for i in [periodic_table.symbol_to_elements, \n periodic_table.number_to_elements,\n periodic_table.CAS_to_elements]:\n if i == periodic_table.number_to_elements:\n if int(ID in i):\n return periodic_table[int(ID)].CAS\n \n else:\n if ID in i:\n return periodic_table[ID].CAS\n\n if checkCAS(ID):\n CAS_lookup = pubchem_db.search_CAS(ID, autoload)\n if CAS_lookup:\n return CAS_lookup.CASs\n \n # handle the case of synonyms\n CAS_alternate_loopup = pubchem_db.search_name(ID, autoload)\n if CAS_alternate_loopup:\n return CAS_alternate_loopup.CASs\n if not autoload:\n return CAS_from_any(ID, autoload=True)\n raise Exception('A valid CAS number was recognized, but is not in the database')\n \n \n \n ID_len = len(ID)\n if ID_len > 9:\n inchi_search = False\n # normal upper case is 'InChI=1S/'\n if ID_lower[0:9] == 'inchi=1s/':\n inchi_search = ID[9:]\n elif ID_lower[0:8] == 'inchi=1/':\n inchi_search = ID[8:]\n if inchi_search:\n inchi_lookup = pubchem_db.search_InChI(inchi_search, autoload)\n if inchi_lookup:\n return inchi_lookup.CASs\n else:\n if not autoload:\n return CAS_from_any(ID, autoload=True)\n raise Exception('A valid InChI name was recognized, but it is not in the database')\n if ID_lower[0:9] == 'inchikey=':\n inchi_key_lookup = pubchem_db.search_InChI_key(ID[9:], autoload)\n if inchi_key_lookup:\n return inchi_key_lookup.CASs\n else:\n if not autoload:\n return CAS_from_any(ID, autoload=True)\n raise Exception('A valid InChI Key was recognized, but it is not in the database')\n if ID_len > 8:\n if ID_lower[0:8] == 'pubchem=':\n pubchem_lookup = pubchem_db.search_pubchem(ID[8:], autoload)\n if pubchem_lookup:\n return pubchem_lookup.CASs\n else:\n if not autoload:\n return CAS_from_any(ID, autoload=True)\n raise Exception('A PubChem integer identifier was recognized, but it is not in the database.')\n if ID_len > 7:\n if ID_lower[0:7] == 'smiles=':\n smiles_lookup = pubchem_db.search_smiles(ID[7:], autoload)\n if smiles_lookup:\n return smiles_lookup.CASs\n else:\n if not autoload:\n return CAS_from_any(ID, autoload=True)\n raise Exception('A SMILES identifier was recognized, but it is not in the database.')\n\n # Try the smiles lookup anyway\n # Parsing SMILES is an option, but this is faster\n # Pybel API also prints messages to console on failure\n smiles_lookup = pubchem_db.search_smiles(ID, autoload)\n if smiles_lookup:\n return smiles_lookup.CASs\n \n try:\n formula_query = pubchem_db.search_formula(serialize_formula(ID), autoload)\n if formula_query and type(formula_query) == ChemicalMetadata:\n return formula_query.CASs\n except:\n pass\n \n # Try a direct lookup with the name - the fastest\n name_lookup = pubchem_db.search_name(ID, autoload)\n if name_lookup:\n return name_lookup.CASs\n\n# Permutate through various name options\n ID_no_space = ID.replace(' ', '')\n ID_no_space_dash = ID_no_space.replace('-', '')\n \n for name in [ID, ID_no_space, ID_no_space_dash]:\n for name2 in [name, name.lower()]:\n name_lookup = pubchem_db.search_name(name2, autoload)\n if name_lookup:\n return name_lookup.CASs\n \n \n if ID[-1] == ')' and '(' in ID:#\n # Try to matck in the form 'water (H2O)'\n first_identifier, second_identifier = ID[0:-1].split('(', 1)\n try:\n CAS1 = CAS_from_any(first_identifier)\n CAS2 = CAS_from_any(second_identifier)\n assert CAS1 == CAS2\n return CAS1\n except:\n pass\n \n if not autoload:\n return CAS_from_any(ID, autoload=True)\n \n raise Exception('Chemical name not recognized')"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef mixture_from_any(ID):\n '''Looks up a string which may represent a mixture in the database of \n thermo to determine the key by which the composition of that mixture can\n be obtained in the dictionary `_MixtureDict`.\n\n Parameters\n ----------\n ID : str\n A string or 1-element list containing the name which may represent a\n mixture.\n\n Returns\n -------\n key : str\n Key for access to the data on the mixture in `_MixtureDict`.\n\n Notes\n -----\n White space, '-', and upper case letters are removed in the search.\n\n Examples\n --------\n >>> mixture_from_any('R512A')\n 'R512A'\n >>> mixture_from_any([u'air'])\n 'Air'\n '''\n if type(ID) == list:\n if len(ID) == 1:\n ID = ID[0]\n else:\n raise Exception('If the input is a list, the list must contain only one item.')\n ID = ID.lower().strip()\n ID2 = ID.replace(' ', '')\n ID3 = ID.replace('-', '')\n for i in [ID, ID2, ID3]:\n if i in _MixtureDictLookup:\n return _MixtureDictLookup[i]\n raise Exception('Mixture name not recognized')", "response": "Returns the key for which the composition of that mixture can be obtained in the dictionary of \n ."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn the charge of the species as an integer.", "response": "def charge(self):\n '''Charge of the species as an integer. Computed as a property as most\n species do not have a charge and so storing it would be a waste of \n memory.\n '''\n try:\n return self._charge\n except AttributeError:\n self._charge = charge_from_formula(self.formula)\n return self._charge"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef load_included_indentifiers(self, file_name):\n '''Loads a file with newline-separated integers representing which \n chemical should be kept in memory; ones not included are ignored.\n '''\n self.restrict_identifiers = True\n included_identifiers = set() \n with open(file_name) as f:\n [included_identifiers.add(int(line)) for line in f]\n self.included_identifiers = included_identifiers", "response": "Loads a file with newline - separated integers representing which \n chemical should be kept in memory ; ones not included are ignored."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef EQ100(T, A=0, B=0, C=0, D=0, E=0, F=0, G=0, order=0):\n r'''DIPPR Equation # 100. Used in calculating the molar heat capacities\n of liquids and solids, liquid thermal conductivity, and solid density.\n All parameters default to zero. As this is a straightforward polynomial,\n no restrictions on parameters apply. Note that high-order polynomials like\n this may need large numbers of decimal places to avoid unnecessary error.\n\n .. math::\n Y = A + BT + CT^2 + DT^3 + ET^4 + FT^5 + GT^6\n\n Parameters\n ----------\n T : float\n Temperature, [K]\n A-G : float\n Parameter for the equation; chemical and property specific [-]\n order : int, optional\n Order of the calculation. 0 for the calculation of the result itself;\n for 1, the first derivative of the property is returned, for\n -1, the indefinite integral of the property with respect to temperature\n is returned; and for -1j, the indefinite integral of the property\n divided by temperature with respect to temperature is returned. No \n other integrals or derivatives are implemented, and an exception will \n be raised if any other order is given.\n\n Returns\n -------\n Y : float\n Property [constant-specific; if order == 1, property/K; if order == -1,\n property*K; if order == -1j, unchanged from default]\n\n Notes\n -----\n The derivative with respect to T, integral with respect to T, and integral\n over T with respect to T are computed as follows. All derivatives and \n integrals are easily computed with SymPy.\n \n .. math::\n \\frac{d Y}{dT} = B + 2 C T + 3 D T^{2} + 4 E T^{3} + 5 F T^{4} \n + 6 G T^{5}\n \n .. math::\n \\int Y dT = A T + \\frac{B T^{2}}{2} + \\frac{C T^{3}}{3} + \\frac{D \n T^{4}}{4} + \\frac{E T^{5}}{5} + \\frac{F T^{6}}{6} + \\frac{G T^{7}}{7}\n \n .. math::\n \\int \\frac{Y}{T} dT = A \\log{\\left (T \\right )} + B T + \\frac{C T^{2}}\n {2} + \\frac{D T^{3}}{3} + \\frac{E T^{4}}{4} + \\frac{F T^{5}}{5} \n + \\frac{G T^{6}}{6}\n\n Examples\n --------\n Water liquid heat capacity; DIPPR coefficients normally listed in J/kmol/K.\n\n >>> EQ100(300, 276370., -2090.1, 8.125, -0.014116, 0.0000093701)\n 75355.81000000003\n\n References\n ----------\n .. [1] Design Institute for Physical Properties, 1996. DIPPR Project 801\n DIPPR/AIChE\n '''\n if order == 0:\n return A + T*(B + T*(C + T*(D + T*(E + T*(F + G*T)))))\n elif order == 1:\n return B + T*(2*C + T*(3*D + T*(4*E + T*(5*F + 6*G*T))))\n elif order == -1:\n return T*(A + T*(B/2 + T*(C/3 + T*(D/4 + T*(E/5 + T*(F/6 + G*T/7))))))\n elif order == -1j:\n return A*log(T) + T*(B + T*(C/2 + T*(D/3 + T*(E/4 + T*(F/5 + G*T/6)))))\n else:\n raise Exception(order_not_found_msg)", "response": "r'''DIPPR Equation # 100. Used in calculating the molar heat capacities of liquids and solids and liquid thermal conductivity."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef EQ104(T, A, B, C, D, E, order=0):\n r'''DIPPR Equation #104. Often used in calculating second virial\n coefficients of gases. All 5 parameters are required.\n C, D, and E are normally large values.\n\n .. math::\n Y = A + \\frac{B}{T} + \\frac{C}{T^3} + \\frac{D}{T^8} + \\frac{E}{T^9}\n\n Parameters\n ----------\n T : float\n Temperature, [K]\n A-E : float\n Parameter for the equation; chemical and property specific [-]\n order : int, optional\n Order of the calculation. 0 for the calculation of the result itself;\n for 1, the first derivative of the property is returned, for\n -1, the indefinite integral of the property with respect to temperature\n is returned; and for -1j, the indefinite integral of the property\n divided by temperature with respect to temperature is returned. No \n other integrals or derivatives are implemented, and an exception will \n be raised if any other order is given.\n\n Returns\n -------\n Y : float\n Property [constant-specific; if order == 1, property/K; if order == -1,\n property*K; if order == -1j, unchanged from default]\n\n Notes\n -----\n The derivative with respect to T, integral with respect to T, and integral\n over T with respect to T are computed as follows. All expressions can be\n obtained with SymPy readily.\n \n .. math::\n \\frac{d Y}{dT} = - \\frac{B}{T^{2}} - \\frac{3 C}{T^{4}} \n - \\frac{8 D}{T^{9}} - \\frac{9 E}{T^{10}}\n \n .. math::\n \\int Y dT = A T + B \\log{\\left (T \\right )} - \\frac{1}{56 T^{8}} \n \\left(28 C T^{6} + 8 D T + 7 E\\right)\n \n .. math::\n \\int \\frac{Y}{T} dT = A \\log{\\left (T \\right )} - \\frac{1}{72 T^{9}} \n \\left(72 B T^{8} + 24 C T^{6} + 9 D T + 8 E\\right)\n\n Examples\n --------\n Water second virial coefficient; DIPPR coefficients normally dimensionless.\n\n >>> EQ104(300, 0.02222, -26.38, -16750000, -3.894E19, 3.133E21)\n -1.1204179007265156\n\n References\n ----------\n .. [1] Design Institute for Physical Properties, 1996. DIPPR Project 801\n DIPPR/AIChE\n '''\n if order == 0:\n T2 = T*T\n return A + (B + (C + (D + E/T)/(T2*T2*T))/T2)/T\n elif order == 1:\n T2 = T*T\n T4 = T2*T2\n return (-B + (-3*C + (-8*D - 9*E/T)/(T4*T))/T2)/T2\n elif order == -1:\n return A*T + B*log(T) - (28*C*T**6 + 8*D*T + 7*E)/(56*T**8)\n elif order == -1j:\n return A*log(T) - (72*B*T**8 + 24*C*T**6 + 9*D*T + 8*E)/(72*T**9)\n else:\n raise Exception(order_not_found_msg)", "response": "r Returns the second virial base class for the given temperature and property."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef EQ106(T, Tc, A, B, C=0, D=0, E=0):\n r'''DIPPR Equation #106. Often used in calculating liquid surface tension,\n and heat of vaporization.\n Only parameters A and B parameters are required; many fits include no\n further parameters. Critical temperature is also required.\n\n .. math::\n Y = A(1-T_r)^{B + C T_r + D T_r^2 + E T_r^3}\n\n Tr = \\frac{T}{Tc}\n\n Parameters\n ----------\n T : float\n Temperature, [K]\n Tc : float\n Critical temperature, [K]\n A-D : float\n Parameter for the equation; chemical and property specific [-]\n\n Returns\n -------\n Y : float\n Property [constant-specific]\n\n Notes\n -----\n The integral could not be found, but the integral over T actually could,\n again in terms of hypergeometric functions.\n\n Examples\n --------\n Water surface tension; DIPPR coefficients normally in Pa*s.\n\n >>> EQ106(300, 647.096, 0.17766, 2.567, -3.3377, 1.9699)\n 0.07231499373541\n\n References\n ----------\n .. [1] Design Institute for Physical Properties, 1996. DIPPR Project 801\n DIPPR/AIChE\n '''\n Tr = T/Tc\n return A*(1. - Tr)**(B + Tr*(C + Tr*(D + E*Tr)))", "response": "r Equation #106. Often used in calculating liquid surface tension and heat of vaporization."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef EQ107(T, A=0, B=0, C=0, D=0, E=0, order=0):\n r'''DIPPR Equation #107. Often used in calculating ideal-gas heat capacity.\n All 5 parameters are required.\n Also called the Aly-Lee equation.\n\n .. math::\n Y = A + B\\left[\\frac{C/T}{\\sinh(C/T)}\\right]^2 + D\\left[\\frac{E/T}{\n \\cosh(E/T)}\\right]^2\n\n Parameters\n ----------\n T : float\n Temperature, [K]\n A-E : float\n Parameter for the equation; chemical and property specific [-]\n order : int, optional\n Order of the calculation. 0 for the calculation of the result itself;\n for 1, the first derivative of the property is returned, for\n -1, the indefinite integral of the property with respect to temperature\n is returned; and for -1j, the indefinite integral of the property\n divided by temperature with respect to temperature is returned. No \n other integrals or derivatives are implemented, and an exception will \n be raised if any other order is given.\n\n Returns\n -------\n Y : float\n Property [constant-specific; if order == 1, property/K; if order == -1,\n property*K; if order == -1j, unchanged from default]\n\n Notes\n -----\n The derivative with respect to T, integral with respect to T, and integral\n over T with respect to T are computed as follows. The derivative is \n obtained via SymPy; the integrals from Wolfram Alpha.\n \n .. math::\n \\frac{d Y}{dT} = \\frac{2 B C^{3} \\cosh{\\left (\\frac{C}{T} \\right )}}\n {T^{4} \\sinh^{3}{\\left (\\frac{C}{T} \\right )}} - \\frac{2 B C^{2}}{T^{3}\n \\sinh^{2}{\\left (\\frac{C}{T} \\right )}} + \\frac{2 D E^{3} \\sinh{\\left\n (\\frac{E}{T} \\right )}}{T^{4} \\cosh^{3}{\\left (\\frac{E}{T} \\right )}} \n - \\frac{2 D E^{2}}{T^{3} \\cosh^{2}{\\left (\\frac{E}{T} \\right )}}\n \n .. math::\n \\int Y dT = A T + \\frac{B C}{\\tanh{\\left (\\frac{C}{T} \\right )}}\n - D E \\tanh{\\left (\\frac{E}{T} \\right )}\n \n .. math::\n \\int \\frac{Y}{T} dT = A \\log{\\left (T \\right )} + \\frac{B C}{T \\tanh{\n \\left (\\frac{C}{T} \\right )}} - B \\log{\\left (\\sinh{\\left (\\frac{C}{T}\n \\right )} \\right )} - \\frac{D E}{T} \\tanh{\\left (\\frac{E}{T} \\right )}\n + D \\log{\\left (\\cosh{\\left (\\frac{E}{T} \\right )} \\right )}\n \n Examples\n --------\n Water ideal gas molar heat capacity; DIPPR coefficients normally in\n J/kmol/K\n\n >>> EQ107(300., 33363., 26790., 2610.5, 8896., 1169.)\n 33585.90452768923\n\n References\n ----------\n .. [1] Design Institute for Physical Properties, 1996. DIPPR Project 801\n DIPPR/AIChE\n .. [2] Aly, Fouad A., and Lloyd L. Lee. \"Self-Consistent Equations for\n Calculating the Ideal Gas Heat Capacity, Enthalpy, and Entropy.\" Fluid\n Phase Equilibria 6, no. 3 (January 1, 1981): 169-79.\n doi:10.1016/0378-3812(81)85002-9.\n '''\n if order == 0:\n return A + B*((C/T)/sinh(C/T))**2 + D*((E/T)/cosh(E/T))**2\n elif order == 1:\n return (2*B*C**3*cosh(C/T)/(T**4*sinh(C/T)**3) \n - 2*B*C**2/(T**3*sinh(C/T)**2) \n + 2*D*E**3*sinh(E/T)/(T**4*cosh(E/T)**3)\n - 2*D*E**2/(T**3*cosh(E/T)**2))\n elif order == -1:\n return A*T + B*C/tanh(C/T) - D*E*tanh(E/T)\n elif order == -1j:\n return (A*log(T) + B*C/tanh(C/T)/T - B*log(sinh(C/T)) \n - D*E*tanh(E/T)/T + D*log(cosh(E/T)))\n else:\n raise Exception(order_not_found_msg)", "response": "r''' DIPPR Equation #107. Often used in calculating ideal - gas heat capacity."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef EQ115(T, A, B, C=0, D=0, E=0):\n r'''DIPPR Equation #115. No major uses; has been used as an alternate\n liquid viscosity expression, and as a model for vapor pressure.\n Only parameters A and B are required.\n\n .. math::\n Y = \\exp\\left(A + \\frac{B}{T} + C\\log T + D T^2 + \\frac{E}{T^2}\\right)\n\n Parameters\n ----------\n T : float\n Temperature, [K]\n A-E : float\n Parameter for the equation; chemical and property specific [-]\n\n Returns\n -------\n Y : float\n Property [constant-specific]\n\n Notes\n -----\n No coefficients found for this expression.\n This function is not integrable for either dT or Y/T dT.\n\n References\n ----------\n .. [1] Design Institute for Physical Properties, 1996. DIPPR Project 801\n DIPPR/AIChE\n '''\n return exp(A+B/T+C*log(T)+D*T**2 + E/T**2)", "response": "r A basic equation for the current language of the language of the liquid viscosity expression."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef CoolProp_T_dependent_property(T, CASRN, prop, phase):\n r'''Calculates a property of a chemical in either the liquid or gas phase\n as a function of temperature only. This means that the property is\n either at 1 atm or along the saturation curve.\n\n Parameters\n ----------\n T : float\n Temperature of the fluid [K]\n CASRN : str\n CAS number of the fluid\n prop : str\n CoolProp string shortcut for desired property\n phase : str\n Either 'l' or 'g' for liquid or gas properties respectively\n\n Returns\n -------\n prop : float\n Desired chemical property, [units]\n\n Notes\n -----\n For liquids above their boiling point, the liquid property is found on the\n saturation line (at higher pressures). Under their boiling point, the\n property is calculated at 1 atm.\n\n No liquid calculations are permitted above the critical temperature.\n\n For gases under the chemical's boiling point, the gas property is found\n on the saturation line (at sub-atmospheric pressures). Above the boiling\n point, the property is calculated at 1 atm.\n\n An exception is raised if the desired CAS is not supported, or if CoolProp\n is not available.\n\n The list of strings acceptable as an input for property types is:\n http://www.coolprop.org/coolprop/HighLevelAPI.html#table-of-string-inputs-to-propssi-function\n\n Examples\n --------\n Water at STP according to IAPWS-95\n\n >>> CoolProp_T_dependent_property(298.15, '7732-18-5', 'D', 'l')\n 997.047636760347\n\n References\n ----------\n .. [1] Bell, Ian H., Jorrit Wronski, Sylvain Quoilin, and Vincent Lemort.\n \"Pure and Pseudo-Pure Fluid Thermophysical Property Evaluation and the\n Open-Source Thermophysical Property Library CoolProp.\" Industrial &\n Engineering Chemistry Research 53, no. 6 (February 12, 2014):\n 2498-2508. doi:10.1021/ie4033999. http://www.coolprop.org/\n '''\n if not has_CoolProp: # pragma: no cover\n raise Exception('CoolProp library is not installed')\n if CASRN not in coolprop_dict:\n raise Exception('CASRN not in list of supported fluids')\n Tc = coolprop_fluids[CASRN].Tc\n T = float(T) # Do not allow custom objects here\n if phase == 'l':\n if T > Tc:\n raise Exception('For liquid properties, must be under the critical temperature.')\n if PhaseSI('T', T, 'P', 101325, CASRN) in [u'liquid', u'supercritical_liquid']:\n return PropsSI(prop, 'T', T, 'P', 101325, CASRN)\n else:\n return PropsSI(prop, 'T', T, 'Q', 0, CASRN)\n elif phase == 'g':\n if PhaseSI('T', T, 'P', 101325, CASRN) == 'gas':\n return PropsSI(prop, 'T', T, 'P', 101325, CASRN)\n else:\n if T < Tc:\n return PropsSI(prop, 'T', T, 'Q', 1, CASRN)\n else:\n # catch supercritical_gas and friends\n return PropsSI(prop, 'T', T, 'P', 101325, CASRN)\n else:\n raise Exception('Error in CoolProp property function')", "response": "r Calculates a property of a fluid in either the liquid or gas phase of a fluid in the system or the system s system s system."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Stockmayer(Tm=None, Tb=None, Tc=None, Zc=None, omega=None,\n CASRN='', AvailableMethods=False, Method=None):\n r'''This function handles the retrieval or calculation a chemical's\n Stockmayer parameter. Values are available from one source with lookup\n based on CASRNs, or can be estimated from 7 CSP methods.\n Will automatically select a data source to use if no Method is provided;\n returns None if the data is not available.\n\n Prefered sources are 'Magalh\u00e3es, Lito, Da Silva, and Silva (2013)' for\n common chemicals which had valies listed in that source, and the CSP method\n `Tee, Gotoh, and Stewart CSP with Tc, omega (1966)` for chemicals which\n don't.\n\n Examples\n --------\n >>> Stockmayer(CASRN='64-17-5')\n 1291.41\n\n Parameters\n ----------\n Tm : float, optional\n Melting temperature of fluid [K]\n Tb : float, optional\n Boiling temperature of fluid [K]\n Tc : float, optional\n Critical temperature, [K]\n Zc : float, optional\n Critical compressibility, [-]\n omega : float, optional\n Acentric factor of compound, [-]\n CASRN : string, optional\n CASRN [-]\n\n Returns\n -------\n epsilon_k : float\n Lennard-Jones depth of potential-energy minimum over k, [K]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain epsilon with the given\n inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n A string for the method name to use, as defined by constants in\n Stockmayer_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n epsilon for the desired chemical, and will return methods instead of\n epsilon\n\n Notes\n -----\n These values are somewhat rough, as they attempt to pigeonhole a chemical\n into L-J behavior.\n\n The tabulated data is from [2]_, for 322 chemicals.\n\n References\n ----------\n .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n Transport Phenomena, Revised 2nd Edition. New York:\n John Wiley & Sons, Inc., 2006\n .. [2] Magalh\u00e3es, Ana L., Patr\u00edcia F. Lito, Francisco A. Da Silva, and\n Carlos M. Silva. \"Simple and Accurate Correlations for Diffusion\n Coefficients of Solutes in Liquids and Supercritical Fluids over Wide\n Ranges of Temperature and Density.\" The Journal of Supercritical Fluids\n 76 (April 2013): 94-114. doi:10.1016/j.supflu.2013.02.002.\n '''\n def list_methods():\n methods = []\n if CASRN in MagalhaesLJ_data.index:\n methods.append(MAGALHAES)\n if Tc and omega:\n methods.append(TEEGOTOSTEWARD2)\n if Tc:\n methods.append(FLYNN)\n methods.append(BSLC)\n methods.append(TEEGOTOSTEWARD1)\n if Tb:\n methods.append(BSLB)\n if Tm:\n methods.append(BSLM)\n if Tc and Zc:\n methods.append(STIELTHODOS)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == FLYNN:\n epsilon = epsilon_Flynn(Tc)\n elif Method == BSLC:\n epsilon = epsilon_Bird_Stewart_Lightfoot_critical(Tc)\n elif Method == BSLB:\n epsilon = epsilon_Bird_Stewart_Lightfoot_boiling(Tb)\n elif Method == BSLM:\n epsilon = epsilon_Bird_Stewart_Lightfoot_melting(Tm)\n elif Method == STIELTHODOS:\n epsilon = epsilon_Stiel_Thodos(Tc, Zc)\n elif Method == TEEGOTOSTEWARD1:\n epsilon = epsilon_Tee_Gotoh_Steward_1(Tc)\n elif Method == TEEGOTOSTEWARD2:\n epsilon = epsilon_Tee_Gotoh_Steward_2(Tc, omega)\n\n elif Method == MAGALHAES:\n epsilon = float(MagalhaesLJ_data.at[CASRN, \"epsilon\"])\n elif Method == NONE:\n epsilon = None\n else:\n raise Exception('Failure in in function')\n return epsilon", "response": "r Returns Stockmayer object for the given parameters."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef molecular_diameter(Tc=None, Pc=None, Vc=None, Zc=None, omega=None,\n Vm=None, Vb=None, CASRN='', AvailableMethods=False, Method=None):\n r'''This function handles the retrieval or calculation a chemical's\n L-J molecular diameter. Values are available from one source with lookup\n based on CASRNs, or can be estimated from 9 CSP methods.\n Will automatically select a data source to use if no Method is provided;\n returns None if the data is not available.\n\n Prefered sources are 'Magalh\u00e3es, Lito, Da Silva, and Silva (2013)' for\n common chemicals which had valies listed in that source, and the CSP method\n `Tee, Gotoh, and Stewart CSP with Tc, Pc, omega (1966)` for chemicals which\n don't.\n\n Examples\n --------\n >>> molecular_diameter(CASRN='64-17-5')\n 4.23738\n\n Parameters\n ----------\n Tc : float, optional\n Critical temperature, [K]\n Pc : float, optional\n Critical pressure, [Pa]\n Vc : float, optional\n Critical volume, [m^3/mol]\n Zc : float, optional\n Critical compressibility, [-]\n omega : float, optional\n Acentric factor of compound, [-]\n Vm : float, optional\n Molar volume of liquid at the melting point of the fluid [K]\n Vb : float, optional\n Molar volume of liquid at the boiling point of the fluid [K]\n CASRN : string, optional\n CASRN [-]\n\n Returns\n -------\n sigma : float\n Lennard-Jones molecular diameter, [Angstrom]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain epsilon with the given\n inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n A string for the method name to use, as defined by constants in\n molecular_diameter_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n sigma for the desired chemical, and will return methods instead of\n sigma\n\n Notes\n -----\n These values are somewhat rough, as they attempt to pigeonhole a chemical\n into L-J behavior.\n\n The tabulated data is from [2]_, for 322 chemicals.\n\n References\n ----------\n .. [1] Bird, R. Byron, Warren E. Stewart, and Edwin N. Lightfoot.\n Transport Phenomena, Revised 2nd Edition. New York:\n John Wiley & Sons, Inc., 2006\n .. [2] Magalh\u00e3es, Ana L., Patr\u00edcia F. Lito, Francisco A. Da Silva, and\n Carlos M. Silva. \"Simple and Accurate Correlations for Diffusion\n Coefficients of Solutes in Liquids and Supercritical Fluids over Wide\n Ranges of Temperature and Density.\" The Journal of Supercritical Fluids\n 76 (April 2013): 94-114. doi:10.1016/j.supflu.2013.02.002.\n '''\n def list_methods():\n methods = []\n if CASRN in MagalhaesLJ_data.index:\n methods.append(MAGALHAES)\n if Tc and Pc and omega:\n methods.append(TEEGOTOSTEWARD4)\n if Tc and Pc:\n methods.append(SILVALIUMACEDO)\n methods.append(BSLC2)\n methods.append(TEEGOTOSTEWARD3)\n if Vc and Zc:\n methods.append(STIELTHODOSMD)\n if Vc:\n methods.append(FLYNN)\n methods.append(BSLC1)\n if Vb:\n methods.append(BSLB)\n if Vm:\n methods.append(BSLM)\n methods.append(NONE)\n return methods\n\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n if Method == FLYNN:\n sigma = sigma_Flynn(Vc)\n elif Method == BSLC1:\n sigma = sigma_Bird_Stewart_Lightfoot_critical_1(Vc)\n elif Method == BSLC2:\n sigma = sigma_Bird_Stewart_Lightfoot_critical_2(Tc, Pc)\n elif Method == TEEGOTOSTEWARD3:\n sigma = sigma_Tee_Gotoh_Steward_1(Tc, Pc)\n elif Method == SILVALIUMACEDO:\n sigma = sigma_Silva_Liu_Macedo(Tc, Pc)\n elif Method == BSLB:\n sigma = sigma_Bird_Stewart_Lightfoot_boiling(Vb)\n elif Method == BSLM:\n sigma = sigma_Bird_Stewart_Lightfoot_melting(Vm)\n elif Method == STIELTHODOSMD:\n sigma = sigma_Stiel_Thodos(Vc, Zc)\n elif Method == TEEGOTOSTEWARD4:\n sigma = sigma_Tee_Gotoh_Steward_2(Tc, Pc, omega)\n elif Method == MAGALHAES:\n sigma = float(MagalhaesLJ_data.at[CASRN, \"sigma\"])\n elif Method == NONE:\n sigma = None\n else:\n raise Exception('Failure in in function')\n return sigma", "response": "r Returns the molecular diameter of a given chemical s base class."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef sigma_Silva_Liu_Macedo(Tc, Pc):\n r'''Calculates Lennard-Jones molecular diameter.\n Uses critical temperature and pressure. CSP method by [1]_.\n\n .. math::\n \\sigma_{LJ}^3 = 0.17791 + 11.779 \\left( \\frac{T_c}{P_c}\\right)\n - 0.049029\\left( \\frac{T_c}{P_c}\\right)^2\n\n Parameters\n ----------\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n\n Returns\n -------\n sigma : float\n Lennard-Jones molecular diameter, [Angstrom]\n\n Notes\n -----\n Pc is originally in bar. An excellent paper. None is \n returned if the polynomial returns a negative number, as in the case of \n 1029.13 K and 3.83 bar.\n\n Examples\n --------\n >>> sigma_Silva_Liu_Macedo(560.1, 4550000)\n 5.164483998730177\n\n References\n ----------\n .. [1] Silva, Carlos M., Hongqin Liu, and Eugenia A. Macedo. \"Models for\n Self-Diffusion Coefficients of Dense Fluids, Including Hydrogen-Bonding\n Substances.\" Chemical Engineering Science 53, no. 13 (July 1, 1998):\n 2423-29. doi:10.1016/S0009-2509(98)00037-2\n '''\n Pc = Pc/1E5 # Pa to bar\n term = 0.17791 + 11.779*(Tc/Pc) - 0.049029 * (Tc/Pc)**2\n if term < 0:\n sigma = None\n else:\n sigma = (term)**(1/3.)\n return sigma", "response": "r Returns the sigma of the base class of the base class of the base class."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef collision_integral_Kim_Monroe(Tstar, l=1, s=1):\n r'''Calculates Lennard-Jones collision integral for any of 16 values of\n (l,j) for the wide range of 0.3 < Tstar < 400. Values are accurate to\n 0.007 % of actual values, but the calculation of actual values is\n computationally intensive and so these simplifications are used, developed\n in [1]_.\n\n .. math::\n \\Omega^{(l,s)*} = A^{(l,s)} + \\sum_{k=1}^6 \\left[ \\frac{B_k^{(l,s)}}\n {(T^*)^k} + C_k^{(l,s)} (\\ln T^*)^k \\right]\n\n Parameters\n ----------\n Tstar : float\n Reduced temperature of the fluid [-]\n l : int\n term\n s : int\n term\n\n\n Returns\n -------\n Omega : float\n Collision integral of A and B\n\n Notes\n -----\n Acceptable pairs of (l,s) are (1, 1), (1, 2), (1, 3), (1, 4), (1, 5),\n (1, 6), (1, 7), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 3), (3, 4),\n (3, 5), and (4, 4).\n\n .. math::\n T^* = \\frac{k_b T}{\\epsilon}\n\n Examples\n --------\n >>> collision_integral_Kim_Monroe(400, 1, 1)\n 0.4141818082392228\n\n References\n ----------\n .. [1] Kim, Sun Ung, and Charles W. Monroe. \"High-Accuracy Calculations of\n Sixteen Collision Integrals for Lennard-Jones (12-6) Gases and Their\n Interpolation to Parameterize Neon, Argon, and Krypton.\" Journal of\n Computational Physics 273 (September 15, 2014): 358-73.\n doi:10.1016/j.jcp.2014.05.018.\n '''\n if (l, s) not in As_collision:\n raise Exception('Input values of l and s are not supported')\n omega = As_collision[(l, s)]\n for ki in range(6):\n Bs = Bs_collision[(l, s)]\n Cs = Cs_collision[(l, s)]\n omega += Bs[ki]/Tstar**(ki+1) + Cs[ki]*log(Tstar)**(ki+1)\n return omega", "response": "r Returns a new base class that calculates the collision integral for any of the given values of l and s."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef omega(CASRN, AvailableMethods=False, Method=None, IgnoreMethods=['LK', 'DEFINITION']):\n r'''This function handles the retrieval of a chemical's acentric factor,\n `omega`, or its calculation from correlations or directly through the\n definition of acentric factor if possible. Requires a known boiling point,\n critical temperature and pressure for use of the correlations. Requires\n accurate vapor pressure data for direct calculation.\n\n Will automatically select a method to use if no Method is provided;\n returns None if the data is not available and cannot be calculated.\n\n .. math::\n \\omega \\equiv -\\log_{10}\\left[\\lim_{T/T_c=0.7}(P^{sat}/P_c)\\right]-1.0\n\n Examples\n --------\n >>> omega(CASRN='64-17-5')\n 0.635\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n omega : float\n Acentric factor of compound\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain omega with the given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n The method name to use. Accepted methods are 'PSRK', 'PD', 'YAWS', \n 'LK', and 'DEFINITION'. All valid values are also held in the list\n omega_methods.\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n omega for the desired chemical, and will return methods instead of\n omega\n IgnoreMethods : list, optional\n A list of methods to ignore in obtaining the full list of methods,\n useful for for performance reasons and ignoring inaccurate methods\n\n Notes\n -----\n A total of five sources are available for this function. They are:\n\n * 'PSRK', a compillation of experimental and estimated data published \n in the Appendix of [15]_, the fourth revision of the PSRK model.\n * 'PD', an older compillation of\n data published in (Passut & Danner, 1973) [16]_.\n * 'YAWS', a large compillation of data from a\n variety of sources; no data points are sourced in the work of [17]_.\n * 'LK', a estimation method for hydrocarbons.\n * 'DEFINITION', based on the definition of omega as\n presented in [1]_, using vapor pressure data.\n\n References\n ----------\n .. [1] Pitzer, K. S., D. Z. Lippmann, R. F. Curl, C. M. Huggins, and\n D. E. Petersen: The Volumetric and Thermodynamic Properties of Fluids.\n II. Compressibility Factor, Vapor Pressure and Entropy of Vaporization.\n J. Am. Chem. Soc., 77: 3433 (1955).\n .. [2] Horstmann, Sven, Anna Jab\u0142oniec, J\u00f6rg Krafczyk, Kai Fischer, and\n J\u00fcrgen Gmehling. \"PSRK Group Contribution Equation of State:\n Comprehensive Revision and Extension IV, Including Critical Constants\n and \u0391-Function Parameters for 1000 Components.\" Fluid Phase Equilibria\n 227, no. 2 (January 25, 2005): 157-64. doi:10.1016/j.fluid.2004.11.002.\n .. [3] Passut, Charles A., and Ronald P. Danner. \"Acentric Factor. A\n Valuable Correlating Parameter for the Properties of Hydrocarbons.\"\n Industrial & Engineering Chemistry Process Design and Development 12,\n no. 3 (July 1, 1973): 365-68. doi:10.1021/i260047a026.\n .. [4] Yaws, Carl L. Thermophysical Properties of Chemicals and\n Hydrocarbons, Second Edition. Amsterdam Boston: Gulf Professional\n Publishing, 2014.\n '''\n def list_methods():\n methods = []\n if CASRN in _crit_PSRKR4.index and not np.isnan(_crit_PSRKR4.at[CASRN, 'omega']):\n methods.append('PSRK')\n if CASRN in _crit_PassutDanner.index and not np.isnan(_crit_PassutDanner.at[CASRN, 'omega']):\n methods.append('PD')\n if CASRN in _crit_Yaws.index and not np.isnan(_crit_Yaws.at[CASRN, 'omega']):\n methods.append('YAWS')\n Tcrit, Pcrit = Tc(CASRN), Pc(CASRN)\n if Tcrit and Pcrit:\n if Tb(CASRN):\n methods.append('LK')\n if VaporPressure(CASRN=CASRN).T_dependent_property(Tcrit*0.7):\n methods.append('DEFINITION') # TODO: better integration\n if IgnoreMethods:\n for Method in IgnoreMethods:\n if Method in methods:\n methods.remove(Method)\n methods.append('NONE')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n if Method == 'PSRK':\n _omega = float(_crit_PSRKR4.at[CASRN, 'omega'])\n elif Method == 'PD':\n _omega = float(_crit_PassutDanner.at[CASRN, 'omega'])\n elif Method == 'YAWS':\n _omega = float(_crit_Yaws.at[CASRN, 'omega'])\n elif Method == 'LK':\n _omega = LK_omega(Tb(CASRN), Tc(CASRN), Pc(CASRN))\n elif Method == 'DEFINITION':\n P = VaporPressure(CASRN=CASRN).T_dependent_property(Tc(CASRN)*0.7)\n _omega = -log10(P/Pc(CASRN)) - 1.0\n elif Method == 'NONE':\n _omega = None\n else:\n raise Exception('Failure in in function')\n return _omega", "response": "r Returns a new structure of the acentric factor of a given CASRN."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nestimate the acentric factor of a base class based on a correlation based on Three - Parameter Corresponding States.", "response": "def LK_omega(Tb, Tc, Pc):\n r'''Estimates the acentric factor of a fluid using a correlation in [1]_.\n\n .. math::\n \\omega = \\frac{\\ln P_{br}^{sat} - 5.92714 + 6.09648/T_{br} + 1.28862\n \\ln T_{br} -0.169347T_{br}^6}\n {15.2518 - 15.6875/T_{br} - 13.4721 \\ln T_{br} + 0.43577 T_{br}^6}\n\n Parameters\n ----------\n Tb : float\n Boiling temperature of the fluid [K]\n Tc : float\n Critical temperature of the fluid [K]\n Pc : float\n Critical pressure of the fluid [Pa]\n\n Returns\n -------\n omega : float\n Acentric factor of the fluid [-]\n\n Notes\n -----\n Internal units are atmosphere and Kelvin.\n Example value from Reid (1987). Using ASPEN V8.4, LK method gives 0.325595.\n\n Examples\n --------\n Isopropylbenzene\n\n >>> LK_omega(425.6, 631.1, 32.1E5)\n 0.32544249926397856\n\n References\n ----------\n .. [1] Lee, Byung Ik, and Michael G. Kesler. \"A Generalized Thermodynamic\n Correlation Based on Three-Parameter Corresponding States.\" AIChE Journal\n 21, no. 3 (1975): 510-527. doi:10.1002/aic.690210313.\n '''\n T_br = Tb/Tc\n omega = (log(101325.0/Pc) - 5.92714 + 6.09648/T_br + 1.28862*log(T_br) -\n 0.169347*T_br**6)/(15.2518 - 15.6875/T_br - 13.4721*log(T_br) +\n 0.43577*T_br**6)\n return omega"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef omega_mixture(omegas, zs, CASRNs=None, Method=None,\n AvailableMethods=False):\n r'''This function handles the calculation of a mixture's acentric factor.\n Calculation is based on the omegas provided for each pure component. Will\n automatically select a method to use if no Method is provided;\n returns None if insufficient data is available.\n\n Examples\n --------\n >>> omega_mixture([0.025, 0.12], [0.3, 0.7])\n 0.0915\n\n Parameters\n ----------\n omegas : array-like\n acentric factors of each component, [-]\n zs : array-like\n mole fractions of each component, [-]\n CASRNs: list of strings\n CASRNs, not currently used [-]\n\n Returns\n -------\n omega : float\n acentric factor of the mixture, [-]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain omega with the given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n The method name to use. Only 'SIMPLE' is accepted so far.\n All valid values are also held in the list omega_mixture_methods.\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n omega for the desired chemical, and will return methods instead of\n omega\n\n Notes\n -----\n The only data used in the methods implemented to date are mole fractions\n and pure-component omegas. An alternate definition could be based on\n the dew point or bubble point of a multicomponent mixture, but this has\n not been done to date.\n\n References\n ----------\n .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n '''\n def list_methods():\n methods = []\n if none_and_length_check([zs, omegas]):\n methods.append('SIMPLE')\n methods.append('NONE')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == 'SIMPLE':\n _omega = mixing_simple(zs, omegas)\n elif Method == 'NONE':\n _omega = None\n else:\n raise Exception('Failure in in function')\n return _omega", "response": "r This function calculates the acentric factor of a multicomponent mixture."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef StielPolar(Tc=None, Pc=None, omega=None, CASRN='', Method=None,\n AvailableMethods=False):\n r'''This function handles the calculation of a chemical's Stiel Polar\n factor, directly through the definition of Stiel-polar factor if possible.\n Requires Tc, Pc, acentric factor, and a vapor pressure datum at Tr=0.6.\n\n Will automatically select a method to use if no Method is provided;\n returns None if the data is not available and cannot be calculated.\n\n .. math::\n x = \\log P_r|_{T_r=0.6} + 1.70 \\omega + 1.552\n\n Parameters\n ----------\n Tc : float\n Critical temperature of fluid [K]\n Pc : float\n Critical pressure of fluid [Pa]\n omega : float\n Acentric factor of the fluid [-]\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n factor : float\n Stiel polar factor of compound\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain Stiel polar factor with the\n given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n The method name to use. Only 'DEFINITION' is accepted so far.\n All valid values are also held in the list Stiel_polar_methods.\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n Stiel-polar factor for the desired chemical, and will return methods\n instead of stiel-polar factor\n\n Notes\n -----\n Only one source is available for this function. It is:\n\n * 'DEFINITION', based on the definition of\n Stiel Polar Factor presented in [1]_, using vapor pressure data.\n\n A few points have also been published in [2]_, which may be used for\n comparison. Currently this is only used for a surface tension correlation.\n\n Examples\n --------\n >>> StielPolar(647.3, 22048321.0, 0.344, CASRN='7732-18-5')\n 0.024581140348734376\n\n References\n ----------\n .. [1] Halm, Roland L., and Leonard I. Stiel. \"A Fourth Parameter for the\n Vapor Pressure and Entropy of Vaporization of Polar Fluids.\" AIChE\n Journal 13, no. 2 (1967): 351-355. doi:10.1002/aic.690130228.\n .. [2] D, Kukoljac Milo\u0161, and Grozdani\u0107 Du\u0161an K. \"New Values of the\n Polarity Factor.\" Journal of the Serbian Chemical Society 65, no. 12\n (January 1, 2000). http://www.shd.org.rs/JSCS/Vol65/No12-Pdf/JSCS12-07.pdf\n '''\n def list_methods():\n methods = []\n if Tc and Pc and omega:\n methods.append('DEFINITION')\n methods.append('NONE')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n if Method == 'DEFINITION':\n P = VaporPressure(CASRN=CASRN).T_dependent_property(Tc*0.6)\n if not P:\n factor = None\n else:\n Pr = P/Pc\n factor = log10(Pr) + 1.70*omega + 1.552\n elif Method == 'NONE':\n factor = None\n else:\n raise Exception('Failure in in function')\n return factor", "response": "r Returns a new Stiel - polar factor for the given chemical."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef VDI_tabular_data(CASRN, prop):\n r'''This function retrieves the tabular data available for a given chemical\n and a given property. Lookup is based on CASRNs. Length of data returned\n varies between chemicals. All data is at saturation condition from [1]_.\n\n Function has data for 58 chemicals.\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n prop : string\n Property [-]\n\n Returns\n -------\n Ts : list\n Temperatures where property data is available, [K]\n props : list\n Properties at each temperature, [various]\n\n Notes\n -----\n The available properties are 'P', 'Density (l)', 'Density (g)', 'Hvap',\n 'Cp (l)', 'Cp (g)', 'Mu (l)', 'Mu (g)', 'K (l)', 'K (g)', 'Pr (l)',\n 'Pr (g)', 'sigma', 'Beta', 'Volume (l)', and 'Volume (g)'.\n\n Data is available for all properties and all chemicals; surface tension\n data was missing for mercury, but added as estimated from the a/b\n coefficients listed in Jasper (1972) to simplify the function.\n\n Examples\n --------\n >>> VDI_tabular_data('67-56-1', 'Mu (g)')\n ([337.63, 360.0, 385.0, 410.0, 435.0, 460.0, 500.0], [1.11e-05, 1.18e-05, 1.27e-05, 1.36e-05, 1.46e-05, 1.59e-05, 2.04e-05])\n\n References\n ----------\n .. [1] Gesellschaft, VDI, ed. VDI Heat Atlas. 2E. Berlin\u202f: Springer, 2010.\n '''\n try:\n d = _VDISaturationDict[CASRN]\n except KeyError:\n raise Exception('CASRN not in VDI tabulation')\n try:\n props, Ts = d[prop], d['T']\n except:\n raise Exception('Proprty not specified correctly')\n Ts = [T for p, T in zip(props, Ts) if p]\n props = [p for p in props if p]\n\n # Not all data series convererge to correct values\n if prop == 'sigma':\n Ts.append(d['Tc'])\n props.append(0)\n return Ts, props", "response": "r Returns the tabular data available for a given CASRN and property."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Yoon_Thodos(T, Tc, Pc, MW):\n r'''Calculates the viscosity of a gas using an emperical formula\n developed in [1]_.\n\n .. math::\n \\eta \\xi \\times 10^8 = 46.10 T_r^{0.618} - 20.40 \\exp(-0.449T_r) + 1\n 9.40\\exp(-4.058T_r)+1\n\n \\xi = 2173.424 T_c^{1/6} MW^{-1/2} P_c^{-2/3}\n\n Parameters\n ----------\n T : float\n Temperature of the fluid [K]\n Tc : float\n Critical temperature of the fluid [K]\n Pc : float\n Critical pressure of the fluid [Pa]\n MW : float\n Molwcular weight of fluid [g/mol]\n\n Returns\n -------\n mu_g : float\n Viscosity of gas, [Pa*S]\n\n Notes\n -----\n This equation has been tested. The equation uses SI units only internally.\n The constant 2173.424 is an adjustment factor for units.\n Average deviation within 3% for most compounds.\n Greatest accuracy with dipole moments close to 0.\n Hydrogen and helium have different coefficients, not implemented.\n This is DIPPR Procedure 8B: Method for the Viscosity of Pure,\n non hydrocarbon, nonpolar gases at low pressures\n\n Examples\n --------\n >>> Yoon_Thodos(300., 556.35, 4.5596E6, 153.8)\n 1.0194885727776819e-05\n\n References\n ----------\n .. [1] Yoon, Poong, and George Thodos. \"Viscosity of Nonpolar Gaseous\n Mixtures at Normal Pressures.\" AIChE Journal 16, no. 2 (1970): 300-304.\n doi:10.1002/aic.690160225.\n '''\n Tr = T/Tc\n xi = 2173.4241*Tc**(1/6.)/(MW**0.5*Pc**(2/3.))\n a = 46.1\n b = 0.618\n c = 20.4\n d = -0.449\n e = 19.4\n f = -4.058\n return (1. + a*Tr**b - c * exp(d*Tr) + e*exp(f*Tr))/(1E8*xi)", "response": "r Returns the viscosity of a given set of non - polar gases at normal pressure."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ncalculate the viscosity of a gas mixture according to the given mixing rules.", "response": "def Wilke(ys, mus, MWs):\n r'''Calculates viscosity of a gas mixture according to\n mixing rules in [1]_.\n\n .. math::\n \\eta_{mix} = \\sum_{i=1}^n \\frac{y_i \\eta_i}{\\sum_{j=1}^n y_j \\phi_{ij}}\n\n \\phi_{ij} = \\frac{(1 + \\sqrt{\\eta_i/\\eta_j}(MW_j/MW_i)^{0.25})^2}\n {\\sqrt{8(1+MW_i/MW_j)}}\n\n Parameters\n ----------\n ys : float\n Mole fractions of gas components\n mus : float\n Gas viscosities of all components, [Pa*S]\n MWs : float\n Molecular weights of all components, [g/mol]\n\n Returns\n -------\n mug : float\n Viscosity of gas mixture, Pa*S]\n\n Notes\n -----\n This equation is entirely dimensionless; all dimensions cancel.\n The original source has not been reviewed or found.\n\n Examples\n --------\n >>> Wilke([0.05, 0.95], [1.34E-5, 9.5029E-6], [64.06, 46.07])\n 9.701614885866193e-06\n\n References\n ----------\n .. [1] TODO\n '''\n if not none_and_length_check([ys, mus, MWs]): # check same-length inputs\n raise Exception('Function inputs are incorrect format')\n cmps = range(len(ys))\n phis = [[(1 + (mus[i]/mus[j])**0.5*(MWs[j]/MWs[i])**0.25)**2/(8*(1 + MWs[i]/MWs[j]))**0.5\n for j in cmps] for i in cmps]\n\n return sum([ys[i]*mus[i]/sum([ys[j]*phis[i][j] for j in cmps]) for i in cmps])"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ncalculating the Brokaw formula for a single resource in the system.", "response": "def Brokaw(T, ys, mus, MWs, molecular_diameters, Stockmayers):\n r'''Calculates viscosity of a gas mixture according to\n mixing rules in [1]_.\n\n .. math::\n \\eta_{mix} = \\sum_{i=1}^n \\frac{y_i \\eta_i}{\\sum_{j=1}^n y_j \\phi_{ij}}\n\n \\phi_{ij} = \\left( \\frac{\\eta_i}{\\eta_j} \\right)^{0.5} S_{ij} A_{ij}\n\n A_{ij} = m_{ij} M_{ij}^{-0.5} \\left[1 +\n \\frac{M_{ij} - M_{ij}^{0.45}}\n {2(1+M_{ij}) + \\frac{(1 + M_{ij}^{0.45}) m_{ij}^{-0.5}}{1 + m_{ij}}} \\right]\n\n m_{ij} = \\left[ \\frac{4}{(1+M_{ij}^{-1})(1+M_{ij})}\\right]^{0.25}\n\n M_{ij} = \\frac{M_i}{M_j}\n\n S_{ij} = \\frac{1 + (T_i^* T_j^*)^{0.5} + (\\delta_i \\delta_j/4)}\n {[1+T_i^* + (\\delta_i^2/4)]^{0.5}[1+T_j^*+(\\delta_j^2/4)]^{0.5}}\n\n T^* = kT/\\epsilon\n\n Parameters\n ----------\n T : float\n Temperature of fluid, [K]\n ys : float\n Mole fractions of gas components\n mus : float\n Gas viscosities of all components, [Pa*S]\n MWs : float\n Molecular weights of all components, [g/mol]\n molecular_diameters : float\n L-J molecular diameter of all components, [angstroms]\n Stockmayers : float\n L-J Stockmayer energy parameters of all components, []\n\n Returns\n -------\n mug : float\n Viscosity of gas mixture, [Pa*S]\n\n Notes\n -----\n This equation is entirely dimensionless; all dimensions cancel.\n The original source has not been reviewed.\n\n This is DIPPR Procedure 8D: Method for the Viscosity of Nonhydrocarbon\n Vapor Mixtures at Low Pressure (Polar and Nonpolar)\n\n Examples\n --------\n >>> Brokaw(308.2, [0.05, 0.95], [1.34E-5, 9.5029E-6], [64.06, 46.07], [0.42, 0.19], [347, 432])\n 9.699085099801568e-06\n\n References\n ----------\n .. [1] Brokaw, R. S. \"Predicting Transport Properties of Dilute Gases.\"\n Industrial & Engineering Chemistry Process Design and Development\n 8, no. 2 (April 1, 1969): 240-53. doi:10.1021/i260030a015.\n .. [2] Brokaw, R. S. Viscosity of Gas Mixtures, NASA-TN-D-4496, 1968.\n .. [3] Danner, Ronald P, and Design Institute for Physical Property Data.\n Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982.\n '''\n cmps = range(len(ys))\n MDs = molecular_diameters\n if not none_and_length_check([ys, mus, MWs, molecular_diameters, Stockmayers]): # check same-length inputs\n raise Exception('Function inputs are incorrect format')\n Tsts = [T/Stockmayer_i for Stockmayer_i in Stockmayers]\n Sij = [[0 for i in cmps] for j in cmps]\n Mij = [[0 for i in cmps] for j in cmps]\n mij = [[0 for i in cmps] for j in cmps]\n Aij = [[0 for i in cmps] for j in cmps]\n phiij =[[0 for i in cmps] for j in cmps]\n\n for i in cmps:\n for j in cmps:\n Sij[i][j] = (1+(Tsts[i]*Tsts[j])**0.5 + (MDs[i]*MDs[j])/4.)/(1 + Tsts[i] + (MDs[i]**2/4.))**0.5/(1 + Tsts[j] + (MDs[j]**2/4.))**0.5\n if MDs[i] <= 0.1 and MDs[j] <= 0.1:\n Sij[i][j] = 1\n Mij[i][j] = MWs[i]/MWs[j]\n mij[i][j] = (4./(1+Mij[i][j]**-1)/(1+Mij[i][j]))**0.25\n\n Aij[i][j] = mij[i][j]*Mij[i][j]**-0.5*(1 + (Mij[i][j]-Mij[i][j]**0.45)/(2*(1+Mij[i][j]) + (1+Mij[i][j]**0.45)*mij[i][j]**-0.5/(1+mij[i][j])))\n\n phiij[i][j] = (mus[i]/mus[j])**0.5*Sij[i][j]*Aij[i][j]\n\n return sum([ys[i]*mus[i]/sum([ys[j]*phiij[i][j] for j in cmps]) for i in cmps])"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef load_all_methods(self):\n r'''Method which picks out coefficients for the specified chemical\n from the various dictionaries and DataFrames storing it. All data is\n stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,\n :obj:`all_methods` and obj:`all_methods_P` as a set of methods for\n which the data exists for.\n\n Called on initialization only. See the source code for the variables at\n which the coefficients are stored. The coefficients can safely be\n altered once the class is initialized. This method can be called again\n to reset the parameters.\n '''\n methods, methods_P = [], []\n Tmins, Tmaxs = [], []\n if has_CoolProp and self.CASRN in coolprop_dict:\n methods.append(COOLPROP); methods_P.append(COOLPROP)\n self.CP_f = coolprop_fluids[self.CASRN]\n Tmins.append(self.CP_f.Tmin); Tmaxs.append(self.CP_f.Tc)\n if self.CASRN in _VDISaturationDict:\n methods.append(VDI_TABULAR)\n Ts, props = VDI_tabular_data(self.CASRN, 'Mu (l)')\n self.VDI_Tmin = Ts[0]\n self.VDI_Tmax = Ts[-1]\n self.tabular_data[VDI_TABULAR] = (Ts, props)\n Tmins.append(self.VDI_Tmin); Tmaxs.append(self.VDI_Tmax)\n if self.CASRN in Dutt_Prasad.index:\n methods.append(DUTT_PRASAD)\n _, A, B, C, self.DUTT_PRASAD_Tmin, self.DUTT_PRASAD_Tmax = _Dutt_Prasad_values[Dutt_Prasad.index.get_loc(self.CASRN)].tolist()\n self.DUTT_PRASAD_coeffs = [A, B, C]\n Tmins.append(self.DUTT_PRASAD_Tmin); Tmaxs.append(self.DUTT_PRASAD_Tmax)\n if self.CASRN in VN3_data.index:\n methods.append(VISWANATH_NATARAJAN_3)\n _, _, A, B, C, self.VISWANATH_NATARAJAN_3_Tmin, self.VISWANATH_NATARAJAN_3_Tmax = _VN3_data_values[VN3_data.index.get_loc(self.CASRN)].tolist()\n self.VISWANATH_NATARAJAN_3_coeffs = [A, B, C]\n Tmins.append(self.VISWANATH_NATARAJAN_3_Tmin); Tmaxs.append(self.VISWANATH_NATARAJAN_3_Tmax)\n if self.CASRN in VN2_data.index:\n methods.append(VISWANATH_NATARAJAN_2)\n _, _, A, B, self.VISWANATH_NATARAJAN_2_Tmin, self.VISWANATH_NATARAJAN_2_Tmax = _VN2_data_values[VN2_data.index.get_loc(self.CASRN)].tolist()\n self.VISWANATH_NATARAJAN_2_coeffs = [A, B]\n Tmins.append(self.VISWANATH_NATARAJAN_2_Tmin); Tmaxs.append(self.VISWANATH_NATARAJAN_2_Tmax)\n if self.CASRN in VN2E_data.index:\n methods.append(VISWANATH_NATARAJAN_2E)\n _, _, C, D, self.VISWANATH_NATARAJAN_2E_Tmin, self.VISWANATH_NATARAJAN_2E_Tmax = _VN2E_data_values[VN2E_data.index.get_loc(self.CASRN)].tolist()\n self.VISWANATH_NATARAJAN_2E_coeffs = [C, D]\n Tmins.append(self.VISWANATH_NATARAJAN_2E_Tmin); Tmaxs.append(self.VISWANATH_NATARAJAN_2E_Tmax)\n if self.CASRN in Perrys2_313.index:\n methods.append(DIPPR_PERRY_8E)\n _, C1, C2, C3, C4, C5, self.Perrys2_313_Tmin, self.Perrys2_313_Tmax = _Perrys2_313_values[Perrys2_313.index.get_loc(self.CASRN)].tolist()\n self.Perrys2_313_coeffs = [C1, C2, C3, C4, C5]\n Tmins.append(self.Perrys2_313_Tmin); Tmaxs.append(self.Perrys2_313_Tmax)\n if self.CASRN in VDI_PPDS_7.index:\n methods.append(VDI_PPDS)\n self.VDI_PPDS_coeffs = _VDI_PPDS_7_values[VDI_PPDS_7.index.get_loc(self.CASRN)].tolist()[2:]\n if all((self.MW, self.Tc, self.Pc, self.omega)):\n methods.append(LETSOU_STIEL)\n Tmins.append(self.Tc/4); Tmaxs.append(self.Tc) # TODO: test model at low T\n if all((self.MW, self.Tm, self.Tc, self.Pc, self.Vc, self.omega, self.Vml)):\n methods.append(PRZEDZIECKI_SRIDHAR)\n Tmins.append(self.Tm); Tmaxs.append(self.Tc) # TODO: test model at Tm\n if all([self.Tc, self.Pc, self.omega]):\n methods_P.append(LUCAS)\n self.all_methods = set(methods)\n self.all_methods_P = set(methods_P)\n if Tmins and Tmaxs:\n self.Tmin, self.Tmax = min(Tmins), max(Tmaxs)", "response": "r This method loads all methods for the specified chemicalicalCOOKIE."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef calculate_P(self, T, P, method):\n r'''Method to calculate pressure-dependent liquid viscosity at\n temperature `T` and pressure `P` with a given method.\n\n This method has no exception handling; see `TP_dependent_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate viscosity, [K]\n P : float\n Pressure at which to calculate viscosity, [K]\n method : str\n Name of the method to use\n\n Returns\n -------\n mu : float\n Viscosity of the liquid at T and P, [Pa*S]\n '''\n if method == LUCAS:\n mu = self.T_dependent_property(T)\n Psat = self.Psat(T) if hasattr(self.Psat, '__call__') else self.Psat\n mu = Lucas(T, P, self.Tc, self.Pc, self.omega, Psat, mu)\n elif method == COOLPROP:\n mu = PropsSI('V', 'T', T, 'P', P, self.CASRN)\n elif method in self.tabular_data:\n mu = self.interpolate_P(T, P, method)\n return mu", "response": "r Method to calculate pressure - dependent liquid viscosity at a given temperature T and pressure P."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef calculate(self, T, P, zs, ws, method):\n r'''Method to calculate viscosity of a liquid mixture at \n temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n `ws` with a given method.\n\n This method has no exception handling; see `mixture_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the property, [K]\n P : float\n Pressure at which to calculate the property, [Pa]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n method : str\n Name of the method to use\n\n Returns\n -------\n mu : float\n Viscosity of the liquid mixture, [Pa*s]\n '''\n if method == MIXING_LOG_MOLAR:\n mus = [i(T, P) for i in self.ViscosityLiquids]\n return mixing_logarithmic(zs, mus)\n elif method == MIXING_LOG_MASS:\n mus = [i(T, P) for i in self.ViscosityLiquids]\n return mixing_logarithmic(ws, mus)\n elif method == LALIBERTE_MU:\n ws = list(ws) ; ws.pop(self.index_w)\n return Laliberte_viscosity(T, ws, self.wCASs)\n else:\n raise Exception('Method not valid')", "response": "r Method to calculate the viscosity of a liquid mixture at \n temperature pressure P mole fractions zs and weight fractions ws."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef calculate(self, T, method):\n r'''Method to calculate low-pressure gas viscosity at\n tempearture `T` with a given method.\n\n This method has no exception handling; see `T_dependent_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature of the gas, [K]\n method : str\n Name of the method to use\n\n Returns\n -------\n mu : float\n Viscosity of the gas at T and a low pressure, [Pa*S]\n '''\n if method == GHARAGHEIZI:\n mu = Gharagheizi_gas_viscosity(T, self.Tc, self.Pc, self.MW)\n elif method == COOLPROP:\n mu = CoolProp_T_dependent_property(T, self.CASRN, 'V', 'g')\n elif method == DIPPR_PERRY_8E:\n mu = EQ102(T, *self.Perrys2_312_coeffs)\n elif method == VDI_PPDS:\n mu = horner(self.VDI_PPDS_coeffs, T)\n elif method == YOON_THODOS:\n mu = Yoon_Thodos(T, self.Tc, self.Pc, self.MW)\n elif method == STIEL_THODOS:\n mu = Stiel_Thodos(T, self.Tc, self.Pc, self.MW)\n elif method == LUCAS_GAS:\n mu = lucas_gas(T, self.Tc, self.Pc, self.Zc, self.MW, self.dipole, CASRN=self.CASRN)\n elif method in self.tabular_data:\n mu = self.interpolate(T, method)\n return mu", "response": "r Method to calculate low - pressure gas viscosity at a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef load_all_methods(self):\n r'''Method to initialize the object by precomputing any values which\n may be used repeatedly and by retrieving mixture-specific variables.\n All data are stored as attributes. This method also sets :obj:`Tmin`, \n :obj:`Tmax`, and :obj:`all_methods` as a set of methods which should \n work to calculate the property.\n\n Called on initialization only. See the source code for the variables at\n which the coefficients are stored. The coefficients can safely be\n altered once the class is initialized. This method can be called again\n to reset the parameters.\n '''\n methods = [SIMPLE] \n if none_and_length_check((self.MWs, self.molecular_diameters, self.Stockmayers)):\n methods.append(BROKAW)\n if none_and_length_check([self.MWs]):\n methods.extend([WILKE, HERNING_ZIPPERER])\n self.all_methods = set(methods)\n Tmins = [i.Tmin for i in self.ViscosityGases if i.Tmin]\n Tmaxs = [i.Tmax for i in self.ViscosityGases if i.Tmax]\n if Tmins:\n self.Tmin = max(Tmins)\n if Tmaxs:\n self.Tmax = max(Tmaxs)", "response": "r Method to initialize the object by precomputing any values which should be used repeatedly and by retrieving any values which should be used repeatedly and by retrieving the mixture - specific variables."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef TWA(CASRN, AvailableMethods=False, Method=None): # pragma: no cover\n '''This function handles the retrieval of Time-Weighted Average limits on worker\n exposure to dangerous chemicals.\n\n This API is considered experimental, and is expected to be removed in a\n future release in favor of a more complete object-oriented interface.\n\n >>> TWA('98-00-0')\n (10.0, 'ppm')\n >>> TWA('1303-00-0')\n (5.0742430905659505e-05, 'ppm')\n >>> TWA('7782-42-5', AvailableMethods=True)\n ['Ontario Limits', 'None']\n '''\n def list_methods():\n methods = []\n if CASRN in _OntarioExposureLimits and (_OntarioExposureLimits[CASRN][\"TWA (ppm)\"] or _OntarioExposureLimits[CASRN][\"TWA (mg/m^3)\"]):\n methods.append(ONTARIO)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == ONTARIO:\n if _OntarioExposureLimits[CASRN][\"TWA (ppm)\"]:\n _TWA = (_OntarioExposureLimits[CASRN][\"TWA (ppm)\"], 'ppm')\n elif _OntarioExposureLimits[CASRN][\"TWA (mg/m^3)\"]:\n _TWA = (_OntarioExposureLimits[CASRN][\"TWA (mg/m^3)\"], 'mg/m^3')\n elif Method == NONE:\n _TWA = None\n else:\n raise Exception('Failure in in function')\n return _TWA", "response": "This function returns a TWA object that can be used to retrieve the Time - Weighted Average limits on worker\n exposure to dangerous chemicals."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef STEL(CASRN, AvailableMethods=False, Method=None): # pragma: no cover\n '''This function handles the retrieval of Short-term Exposure Limit on\n worker exposure to dangerous chemicals.\n\n This API is considered experimental, and is expected to be removed in a\n future release in favor of a more complete object-oriented interface.\n\n >>> STEL('67-64-1')\n (750.0, 'ppm')\n >>> STEL('7664-38-2')\n (0.7489774978301237, 'ppm')\n >>> STEL('55720-99-5')\n (2.0, 'mg/m^3')\n >>> STEL('86290-81-5', AvailableMethods=True)\n ['Ontario Limits', 'None']\n '''\n def list_methods():\n methods = []\n if CASRN in _OntarioExposureLimits and (_OntarioExposureLimits[CASRN][\"STEL (ppm)\"] or _OntarioExposureLimits[CASRN][\"STEL (mg/m^3)\"]):\n methods.append(ONTARIO)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == ONTARIO:\n if _OntarioExposureLimits[CASRN][\"STEL (ppm)\"]:\n _STEL = (_OntarioExposureLimits[CASRN][\"STEL (ppm)\"], 'ppm')\n elif _OntarioExposureLimits[CASRN][\"STEL (mg/m^3)\"]:\n _STEL = (_OntarioExposureLimits[CASRN][\"STEL (mg/m^3)\"], 'mg/m^3')\n elif Method == NONE:\n _STEL = None\n else:\n raise Exception('Failure in in function')\n return _STEL", "response": "This function returns a STEL object for the given CASRN."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Tautoignition(CASRN, AvailableMethods=False, Method=None):\n r'''This function handles the retrieval or calculation of a chemical's\n autoifnition temperature. Lookup is based on CASRNs. No predictive methods\n are currently implemented. Will automatically select a data source to use\n if no Method is provided; returns None if the data is not available.\n\n Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n 'NFPA 497 (2008)' [2]_ having very similar data.\n\n Examples\n --------\n >>> Tautoignition(CASRN='71-43-2')\n 771.15\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n Tautoignition : float\n Autoignition point of the chemical, [K]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain Tautoignition with the\n given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n A string for the method name to use, as defined by constants in\n Tautoignition_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n Tautoignition for the desired chemical, and will return methods\n instead of Tautoignition\n\n Notes\n -----\n\n References\n ----------\n .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n Material characteristics for gas and vapour classification - Test\n methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n .. [2] National Fire Protection Association. NFPA 497: Recommended\n Practice for the Classification of Flammable Liquids, Gases, or Vapors\n and of Hazardous. NFPA, 2008.\n '''\n def list_methods():\n methods = []\n if CASRN in IEC_2010.index and not np.isnan(IEC_2010.at[CASRN, 'Tautoignition']):\n methods.append(IEC)\n if CASRN in NFPA_2008.index and not np.isnan(NFPA_2008.at[CASRN, 'Tautoignition']):\n methods.append(NFPA)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == IEC:\n return float(IEC_2010.at[CASRN, 'Tautoignition'])\n elif Method == NFPA:\n return float(NFPA_2008.at[CASRN, 'Tautoignition'])\n elif Method == NONE:\n return None\n else:\n raise Exception('Failure in in function')", "response": "r Returns a string that can be used to obtain a Tautoignition for a given chemical."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef LFL(Hc=None, atoms={}, CASRN='', AvailableMethods=False, Method=None):\n r'''This function handles the retrieval or calculation of a chemical's\n Lower Flammability Limit. Lookup is based on CASRNs. Two predictive methods\n are currently implemented. Will automatically select a data source to use\n if no Method is provided; returns None if the data is not available.\n\n Prefered source is 'IEC 60079-20-1 (2010)' [1]_, with the secondary source\n 'NFPA 497 (2008)' [2]_ having very similar data. If the heat of combustion\n is provided, the estimation method `Suzuki_LFL` can be used. If the atoms\n of the molecule are available, the method `Crowl_Louvar_LFL` can be used.\n\n Examples\n --------\n >>> LFL(CASRN='71-43-2')\n 0.012\n\n Parameters\n ----------\n Hc : float, optional\n Heat of combustion of gas [J/mol]\n atoms : dict, optional\n Dictionary of atoms and atom counts\n CASRN : string, optional\n CASRN [-]\n\n Returns\n -------\n LFL : float\n Lower flammability limit of the gas in an atmosphere at STP, [mole fraction]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain LFL with the\n given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n A string for the method name to use, as defined by constants in\n LFL_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n the Lower Flammability Limit for the desired chemical, and will return\n methods instead of Lower Flammability Limit.\n\n Notes\n -----\n\n References\n ----------\n .. [1] IEC. \u201cIEC 60079-20-1:2010 Explosive atmospheres - Part 20-1:\n Material characteristics for gas and vapour classification - Test\n methods and data.\u201d https://webstore.iec.ch/publication/635. See also\n https://law.resource.org/pub/in/bis/S05/is.iec.60079.20.1.2010.pdf\n .. [2] National Fire Protection Association. NFPA 497: Recommended\n Practice for the Classification of Flammable Liquids, Gases, or Vapors\n and of Hazardous. NFPA, 2008.\n '''\n def list_methods():\n methods = []\n if CASRN in IEC_2010.index and not np.isnan(IEC_2010.at[CASRN, 'LFL']):\n methods.append(IEC)\n if CASRN in NFPA_2008.index and not np.isnan(NFPA_2008.at[CASRN, 'LFL']):\n methods.append(NFPA)\n if Hc:\n methods.append(SUZUKI)\n if atoms:\n methods.append(CROWLLOUVAR)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == IEC:\n return float(IEC_2010.at[CASRN, 'LFL'])\n elif Method == NFPA:\n return float(NFPA_2008.at[CASRN, 'LFL'])\n elif Method == SUZUKI:\n return Suzuki_LFL(Hc=Hc)\n elif Method == CROWLLOUVAR:\n return Crowl_Louvar_LFL(atoms=atoms)\n elif Method == NONE:\n return None\n else:\n raise Exception('Failure in in function')", "response": "r Returns a new object that can be used to obtain the LFL of the given chemical s base class and the given atom counts and CASRN."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef LFL_mixture(ys=None, LFLs=None, CASRNs=None, AvailableMethods=False,\n Method=None): # pragma: no cover\n '''Inert gases are ignored.\n\n This API is considered experimental, and is expected to be removed in a\n future release in favor of a more complete object-oriented interface.\n\n >>> LFL_mixture(ys=normalize([0.0024, 0.0061, 0.0015]), LFLs=[.012, .053, .031])\n 0.02751172136637643\n >>> LFL_mixture(LFLs=[None, None, None, None, None, None, None, None, None, None, None, None, None, None, 0.025, 0.06, 0.073, 0.020039, 0.011316], ys=[0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.10, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05], CASRNs=['7440-37-1', '124-38-9', '7440-59-7', '7440-01-9', '7727-37-9', '7440-63-3', '10102-43-9', '7782-44-7', '132259-10-0', '7439-90-9', '10043-92-2', '7732-18-5', '7782-50-5', '7782-41-4', '67-64-1', '67-56-1', '75-52-5', '590-19-2', '277-10-1'])\n 0.023964903630937385\n '''\n def list_methods():\n methods = []\n if CASRNs:\n CASRNs2 = list(CASRNs)\n LFLs2 = list(LFLs)\n for i in inerts:\n if i in CASRNs2:\n ind = CASRNs.index(i)\n CASRNs2.remove(i)\n LFLs2.remove(LFLs[ind])\n if none_and_length_check([LFLs2]):\n methods.append('Summed Inverse, inerts removed')\n else:\n if none_and_length_check([LFLs]):\n methods.append('Summed Inverse')\n methods.append('None')\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n # This is the calculate, given the method section\n# if not none_and_length_check([LFLs, ys]):\n# raise Exception('Function inputs are incorrect format')\n if Method == 'Summed Inverse':\n return fire_mixing(ys, LFLs)\n elif Method == 'Summed Inverse, inerts removed':\n CASRNs2 = list(CASRNs)\n LFLs2 = list(LFLs)\n ys2 = list(ys)\n for i in inerts:\n if i in CASRNs2:\n ind = CASRNs2.index(i)\n CASRNs2.remove(i)\n LFLs2.pop(ind)\n ys2.pop(ind)\n return fire_mixing(normalize(ys2), LFLs2)\n elif Method == 'None':\n return None\n else:\n raise Exception('Failure in in function')", "response": "A version of the LFL mixture for inert gases."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef Crowl_Louvar_LFL(atoms):\n r'''Calculates lower flammability limit, using the Crowl-Louvar [1]_\n correlation. Uses molecular formula only.\n\n The lower flammability limit of a gas is air is:\n\n .. math::\n C_mH_xO_y + zO_2 \\to mCO_2 + \\frac{x}{2}H_2O\n\n \\text{LFL} = \\frac{0.55}{4.76m + 1.19x - 2.38y + 1}\n\n Parameters\n ----------\n atoms : dict\n Dictionary of atoms and atom counts\n\n Returns\n -------\n LFL : float\n Lower flammability limit, mole fraction\n\n Notes\n -----\n Coefficient of 0.55 taken from [2]_\n\n Examples\n --------\n Hexane, example from [1]_, lit. 1.2 %\n\n >>> Crowl_Louvar_LFL({'H': 14, 'C': 6})\n 0.011899610558199915\n\n References\n ----------\n .. [1] Crowl, Daniel A., and Joseph F. Louvar. Chemical Process Safety:\n Fundamentals with Applications. 2E. Upper Saddle River, N.J:\n Prentice Hall, 2001.\n .. [2] Jones, G. W. \"Inflammation Limits and Their Practical Application\n in Hazardous Industrial Operations.\" Chemical Reviews 22, no. 1\n (February 1, 1938): 1-26. doi:10.1021/cr60071a001\n '''\n nC, nH, nO = 0, 0, 0\n if 'C' in atoms and atoms['C']:\n nC = atoms['C']\n else:\n return None\n if 'H' in atoms:\n nH = atoms['H']\n if 'O' in atoms:\n nO = atoms['O']\n return 0.55/(4.76*nC + 1.19*nH - 2.38*nO + 1.)", "response": "r Calculates the lower flammability limit of a Crowl - Louvar formula."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Crowl_Louvar_UFL(atoms):\n r'''Calculates upper flammability limit, using the Crowl-Louvar [1]_\n correlation. Uses molecular formula only.\n\n The upper flammability limit of a gas is air is:\n\n .. math::\n C_mH_xO_y + zO_2 \\to mCO_2 + \\frac{x}{2}H_2O\n\n \\text{UFL} = \\frac{3.5}{4.76m + 1.19x - 2.38y + 1}\n\n Parameters\n ----------\n atoms : dict\n Dictionary of atoms and atom counts\n\n Returns\n -------\n UFL : float\n Upper flammability limit, mole fraction\n\n Notes\n -----\n Coefficient of 3.5 taken from [2]_\n\n Examples\n --------\n Hexane, example from [1]_, lit. 7.5 %\n\n >>> Crowl_Louvar_UFL({'H': 14, 'C': 6})\n 0.07572479446127219\n\n References\n ----------\n .. [1] Crowl, Daniel A., and Joseph F. Louvar. Chemical Process Safety:\n Fundamentals with Applications. 2E. Upper Saddle River, N.J:\n Prentice Hall, 2001.\n .. [2] Jones, G. W. \"Inflammation Limits and Their Practical Application\n in Hazardous Industrial Operations.\" Chemical Reviews 22, no. 1\n (February 1, 1938): 1-26. doi:10.1021/cr60071a001\n '''\n nC, nH, nO = 0, 0, 0\n if 'C' in atoms and atoms['C']:\n nC = atoms['C']\n else:\n return None\n if 'H' in atoms:\n nH = atoms['H']\n if 'O' in atoms:\n nO = atoms['O']\n return 3.5/(4.76*nC + 1.19*nH - 2.38*nO + 1.)", "response": "r Calculates the upper flammability limit of a Crowl - Louvar object."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Vfgs(self, T=None, P=None):\n r'''Volume fractions of all species in a hypothetical pure-gas phase \n at the current or specified temperature and pressure. If temperature \n or pressure are specified, the non-specified property is assumed to be \n that of the mixture. Note this is a method, not a property. Volume \n fractions are calculated based on **pure species volumes only**.\n\n Examples\n --------\n >>> Mixture(['sulfur hexafluoride', 'methane'], zs=[.2, .9], T=315).Vfgs()\n [0.18062059238682632, 0.8193794076131737]\n \n >>> S = Mixture(['sulfur hexafluoride', 'methane'], zs=[.1, .9])\n >>> S.Vfgs(P=1E2)\n [0.0999987466608421, 0.9000012533391578]\n '''\n if (T is None or T == self.T) and (P is None or P == self.P):\n Vmgs = self.Vmgs\n else:\n if T is None: T = self.T\n if P is None: P = self.P\n Vmgs = [i(T, P) for i in self.VolumeGases]\n if none_and_length_check([Vmgs]):\n return zs_to_Vfs(self.zs, Vmgs)\n return None", "response": "r Returns the volume fractions of all species in a hypothetical pure - gas phase \n at the current or specified temperature and pressure."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef mass_fractions(self):\n r'''Dictionary of mass fractions for each atom in the mixture.\n\n Examples\n --------\n >>> Mixture(['CO2', 'O2'], zs=[0.5, 0.5]).mass_fractions\n {'C': 0.15801826905745822, 'O': 0.8419817309425419}\n '''\n things = dict()\n for zi, atoms in zip(self.zs, self.atomss):\n for atom, count in atoms.iteritems():\n if atom in things:\n things[atom] += zi*count\n else:\n things[atom] = zi*count\n return mass_fractions(things)", "response": "Dictionary of mass fractions for each atom in the mixture."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef charge_balance(self):\n r'''Charge imbalance of the mixture, in units of [faraday].\n Mixtures meeting the electroneutrality condition will have an imbalance\n of 0.\n\n Examples\n --------\n >>> Mixture(['Na+', 'Cl-', 'water'], zs=[.01, .01, .98]).charge_balance\n 0.0\n '''\n return sum([zi*ci for zi, ci in zip(self.zs, self.charges)])", "response": "Charge imbalance of the mixture in units of [ faraday ]."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Cpgm(self):\n r'''Gas-phase heat capacity of the mixture at its current temperature\n and composition, in units of [J/mol/K]. For calculation of this property\n at other temperatures or compositions, or specifying manually the\n method used to calculate it, and more - see the object oriented\n interface :obj:`thermo.heat_capacity.HeatCapacityGasMixture`; each\n Mixture instance creates one to actually perform the calculations.\n\n Examples\n --------\n >>> Mixture(['oxygen', 'nitrogen'], ws=[.4, .6], T=350, P=1E6).Cpgm\n 29.361044582498046\n '''\n return self.HeatCapacityGasMixture(self.T, self.P, self.zs, self.ws)", "response": "Returns a new object with the gas - phase heat capacity of the mixture at the current temperature\n and composition in units of [ J / molK ]."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the molar property of the current object s heat capacity.", "response": "def Cpl(self):\n r'''Liquid-phase heat capacity of the mixture at its current\n temperature and composition, in units of [J/kg/K]. For calculation of\n this property at other temperatures or compositions, or specifying\n manually the method used to calculate it, and more - see the object\n oriented interface :obj:`thermo.heat_capacity.HeatCapacityLiquidMixture`;\n each Mixture instance creates one to actually perform the calculations.\n Note that that interface provides output in molar units.\n\n Examples\n --------\n >>> Mixture(['water', 'sodium chloride'], ws=[.9, .1], T=301.5).Cpl\n 3735.4604049449786\n '''\n Cplm = self.HeatCapacityLiquidMixture(self.T, self.P, self.zs, self.ws)\n if Cplm:\n return property_molar_to_mass(Cplm, self.MW)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns the gas - phase heat capacity of the mixture at the specified current temperature.", "response": "def Cpg(self):\n r'''Gas-phase heat capacity of the mixture at its current temperature ,\n and composition in units of [J/kg/K]. For calculation of this property at\n other temperatures or compositions, or specifying manually the method\n used to calculate it, and more - see the object oriented interface\n :obj:`thermo.heat_capacity.HeatCapacityGasMixture`; each Mixture\n instance creates one to actually perform the calculations. Note that\n that interface provides output in molar units.\n\n Examples\n --------\n >>> Mixture(['oxygen', 'nitrogen'], ws=[.4, .6], T=350, P=1E6).Cpg\n 995.8911053614883\n '''\n Cpgm = self.HeatCapacityGasMixture(self.T, self.P, self.zs, self.ws)\n if Cpgm:\n return property_molar_to_mass(Cpgm, self.MW)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning the gas - phase ideal - gas contant - volume heat capacity of the mixture at .", "response": "def Cvgm(self):\n r'''Gas-phase ideal-gas contant-volume heat capacity of the mixture at\n its current temperature and composition, in units of [J/mol/K]. Subtracts R from\n the ideal-gas heat capacity; does not include pressure-compensation\n from an equation of state.\n\n Examples\n --------\n >>> Mixture(['water'], ws=[1], T=520).Cvgm\n 27.13366316134193\n '''\n Cpgm = self.HeatCapacityGasMixture(self.T, self.P, self.zs, self.ws)\n if Cpgm:\n return Cpgm - R\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Vml(self):\n r'''Liquid-phase molar volume of the mixture at its current\n temperature, pressure, and composition in units of [m^3/mol]. For\n calculation of this property at other temperatures or pressures or\n compositions, or specifying manually the method used to calculate it,\n and more - see the object oriented interface\n :obj:`thermo.volume.VolumeLiquidMixture`; each Mixture instance\n creates one to actually perform the calculations.\n\n Examples\n --------\n >>> Mixture(['cyclobutane'], ws=[1], T=225).Vml\n 7.42395423425395e-05\n '''\n return self.VolumeLiquidMixture(T=self.T, P=self.P, zs=self.zs, ws=self.ws)", "response": "Liquid - phase molar volume of the current mixture at the specified species."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Vmg(self):\n r'''Gas-phase molar volume of the mixture at its current\n temperature, pressure, and composition in units of [m^3/mol]. For\n calculation of this property at other temperatures or pressures or\n compositions, or specifying manually the method used to calculate it,\n and more - see the object oriented interface\n :obj:`thermo.volume.VolumeGasMixture`; each Mixture instance\n creates one to actually perform the calculations.\n\n Examples\n --------\n >>> Mixture(['hexane'], ws=[1], T=300, P=2E5).Vmg\n 0.010888694235142216\n '''\n return self.VolumeGasMixture(T=self.T, P=self.P, zs=self.zs, ws=self.ws)", "response": "Returns the gas - phase molar volume of the mixture at the current\n ."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn the SG of the current object.", "response": "def SGg(self):\n r'''Specific gravity of a hypothetical gas phase of the mixture, .\n [dimensionless]. The reference condition is air at 15.6 \u00b0C (60 \u00b0F) and \n 1 atm (rho=1.223 kg/m^3). The definition for gases uses the \n compressibility factor of the reference gas and the mixture both at the \n reference conditions, not the conditions of the mixture.\n \n Examples\n --------\n >>> Mixture('argon').SGg\n 1.3800407778218216\n '''\n Vmg = self.VolumeGasMixture(T=288.70555555555552, P=101325, zs=self.zs, ws=self.ws)\n if Vmg:\n rho = Vm_to_rho(Vmg, self.MW)\n return SG(rho, rho_ref=1.2231876628642968) # calculated with Mixture\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsurfacing tension of the mixture at its current temperature and composition in units of [ N m ).", "response": "def sigma(self):\n r'''Surface tension of the mixture at its current temperature and\n composition, in units of [N/m].\n\n For calculation of this property at other temperatures,\n or specifying manually the method used to calculate it, and more - see\n the object oriented interface :obj:`thermo.interface.SurfaceTensionMixture`;\n each Mixture instance creates one to actually perform the calculations.\n\n Examples\n --------\n >>> Mixture(['water'], ws=[1], T=300, P=1E5).sigma\n 0.07176932405246211\n '''\n return self.SurfaceTensionMixture(self.T, self.P, self.zs, self.ws)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns the thermal conductivity of the mixture in the liquid phase at the current system.", "response": "def kl(self):\n r'''Thermal conductivity of the mixture in the liquid phase at its current\n temperature, pressure, and composition in units of [Pa*s].\n\n For calculation of this property at other temperatures and pressures,\n or specifying manually the method used to calculate it, and more - see\n the object oriented interface\n :obj:`thermo.thermal_conductivity.ThermalConductivityLiquidMixture`;\n each Mixture instance creates one to actually perform the calculations.\n\n Examples\n --------\n >>> Mixture(['water'], ws=[1], T=320).kl\n 0.6369957248212118\n '''\n return self.ThermalConductivityLiquidMixture(self.T, self.P, self.zs, self.ws)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef kg(self):\n r'''Thermal conductivity of the mixture in the gas phase at its current\n temperature, pressure, and composition in units of [Pa*s].\n\n For calculation of this property at other temperatures and pressures,\n or specifying manually the method used to calculate it, and more - see\n the object oriented interface\n :obj:`thermo.thermal_conductivity.ThermalConductivityGasMixture`;\n each Mixture instance creates one to actually perform the calculations.\n\n Examples\n --------\n >>> Mixture(['water'], ws=[1], T=500).kg\n 0.036035173297862676\n '''\n return self.ThermalConductivityGasMixture(self.T, self.P, self.zs, self.ws)", "response": "Returns the thermal conductivity of the mixture in the gas phase at its current\n temperature pressure and composition in units of [ Pa * s ]."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef SG(self):\n r'''Specific gravity of the mixture, [dimensionless]. \n \n For gas-phase conditions, this is calculated at 15.6 \u00b0C (60 \u00b0F) and 1 \n atm for the mixture and the reference fluid, air. \n For liquid and solid phase conditions, this is calculated based on a \n reference fluid of water at 4\u00b0C at 1 atm, but the with the liquid or \n solid mixture's density at the currently specified conditions.\n\n Examples\n --------\n >>> Mixture('MTBE').SG\n 0.7428160596603596\n '''\n return phase_select_property(phase=self.phase, s=self.SGs, l=self.SGl, g=self.SGg)", "response": "Specific gravity of the mixture."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef Vml_STP(self):\n r'''Liquid-phase molar volume of the mixture at 298.15 K and 101.325 kPa,\n and the current composition in units of [m^3/mol].\n\n Examples\n --------\n >>> Mixture(['cyclobutane'], ws=[1]).Vml_STP\n 8.143327329133706e-05\n '''\n return self.VolumeLiquidMixture(T=298.15, P=101325, zs=self.zs, ws=self.ws)", "response": "Liquid - phase molar volume of the mixture at 298. 15 K and 101. 325 kPa."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef Vmg_STP(self):\n r'''Gas-phase molar volume of the mixture at 298.15 K and 101.325 kPa,\n and the current composition in units of [m^3/mol].\n\n Examples\n --------\n >>> Mixture(['nitrogen'], ws=[1]).Vmg_STP\n 0.02445443688838904\n '''\n return self.VolumeGasMixture(T=298.15, P=101325, zs=self.zs, ws=self.ws)", "response": "Returns the gas - phase molar volume of the mixture at 298. 15 K and 101. 325 kPa."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the current rhol - phase mass density of the mixture at 298. 15 K and 101. 325 kPa.", "response": "def rhol_STP(self):\n r'''Liquid-phase mass density of the mixture at 298.15 K and 101.325 kPa,\n and the current composition in units of [kg/m^3].\n\n Examples\n --------\n >>> Mixture(['cyclobutane'], ws=[1]).rhol_STP\n 688.9851989526821\n '''\n Vml = self.Vml_STP\n if Vml:\n return Vm_to_rho(Vml, self.MW)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef rhog_STP(self):\n r'''Gas-phase mass density of the mixture at 298.15 K and 101.325 kPa,\n and the current composition in units of [kg/m^3].\n\n Examples\n --------\n >>> Mixture(['nitrogen'], ws=[1]).rhog_STP\n 1.145534453639403\n '''\n Vmg = self.Vmg_STP\n if Vmg:\n return Vm_to_rho(Vmg, self.MW)\n return None", "response": "Return the gas - phase mass density of the mixture at 298. 15 K and 101. 325 kPa and the current composition in units of [ kM^3 kPa."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the gas - phase compressibility factor of the mixture at 298. 15 K and 101. 325 kPa and the current composition.", "response": "def Zg_STP(self):\n r'''Gas-phase compressibility factor of the mixture at 298.15 K and 101.325 kPa,\n and the current composition, [dimensionless].\n\n Examples\n --------\n >>> Mixture(['nitrogen'], ws=[1]).Zg_STP\n 0.9995520809691023\n '''\n Vmg = self.Vmg\n if Vmg:\n return Z(self.T, self.P, Vmg)\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning the API gravity of the hypothetical liquid phase of the mixture.", "response": "def API(self):\n r'''API gravity of the hypothetical liquid phase of the mixture, \n [degrees]. The reference condition is water at 15.6 \u00b0C (60 \u00b0F) and 1 atm \n (rho=999.016 kg/m^3, standardized).\n \n Examples\n --------\n >>> Mixture(['hexane', 'decane'], ws=[0.5, 0.5]).API\n 71.34707841728181\n '''\n Vml = self.VolumeLiquidMixture(T=288.70555555555552, P=101325, zs=self.zs, ws=self.ws)\n if Vml:\n rho = Vm_to_rho(Vml, self.MW)\n sg = SG(rho, rho_ref=999.016)\n return SG_to_API(sg)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ninterface for drawing a 2D image of all the molecules in the current set of species.", "response": "def draw_2d(self, Hs=False): # pragma: no cover\n r'''Interface for drawing a 2D image of all the molecules in the\n mixture. Requires an HTML5 browser, and the libraries RDKit and\n IPython. An exception is raised if either of these libraries is\n absent.\n\n Parameters\n ----------\n Hs : bool\n Whether or not to show hydrogen\n\n Examples\n --------\n Mixture(['natural gas']).draw_2d()\n '''\n try:\n from rdkit.Chem import Draw\n from rdkit.Chem.Draw import IPythonConsole\n if Hs:\n mols = [i.rdkitmol_Hs for i in self.Chemicals]\n else:\n mols = [i.rdkitmol for i in self.Chemicals]\n return Draw.MolsToImage(mols)\n except:\n return 'Rdkit is required for this feature.'"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef Pt(CASRN, AvailableMethods=False, Method=None):\n r'''This function handles the retrieval of a chemical's triple pressure.\n Lookup is based on CASRNs. Will automatically select a data source to use\n if no Method is provided; returns None if the data is not available.\n\n Returns data from [1]_, or attempts to calculate the vapor pressure at the\n triple temperature, if data is available.\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n Pt : float\n Triple point pressure, [Pa]\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain Pt with the\n given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n A string for the method name to use, as defined by constants in\n Pt_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n the Pt for the desired chemical, and will return methods\n instead of the Pt\n\n Notes\n -----\n\n Examples\n --------\n Ammonia\n\n >>> Pt('7664-41-7')\n 6079.5\n\n References\n ----------\n .. [1] Staveley, L. A. K., L. Q. Lobo, and J. C. G. Calado. \"Triple-Points\n of Low Melting Substances and Their Use in Cryogenic Work.\" Cryogenics\n 21, no. 3 (March 1981): 131-144. doi:10.1016/0011-2275(81)90264-2.\n '''\n def list_methods():\n methods = []\n if CASRN in Staveley_data.index and not np.isnan(Staveley_data.at[CASRN, 'Pt']):\n methods.append(STAVELEY)\n if Tt(CASRN) and VaporPressure(CASRN=CASRN).T_dependent_property(T=Tt(CASRN)):\n methods.append(DEFINITION)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == STAVELEY:\n Pt = Staveley_data.at[CASRN, 'Pt']\n elif Method == DEFINITION:\n Pt = VaporPressure(CASRN=CASRN).T_dependent_property(T=Tt(CASRN))\n elif Method == NONE:\n Pt = None\n else:\n raise Exception('Failure in in function')\n return Pt", "response": "r This function returns the data for a given chemical s triple pressure at the given CASRN."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef to_num(values):\n r'''Legacy function to turn a list of strings into either floats\n (if numeric), stripped strings (if not) or None if the string is empty.\n Accepts any numeric formatting the float function does.\n\n Parameters\n ----------\n values : list\n list of strings\n\n Returns\n -------\n values : list\n list of floats, strings, and None values [-]\n\n Examples\n --------\n >>> to_num(['1', '1.1', '1E5', '0xB4', ''])\n [1.0, 1.1, 100000.0, '0xB4', None]\n '''\n for i in range(len(values)):\n try:\n values[i] = float(values[i])\n except:\n if values[i] == '':\n values[i] = None\n else:\n values[i] = values[i].strip()\n pass\n return values", "response": "Legacy function to turn a list of strings into either floats or stripped strings."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Parachor(MW, rhol, rhog, sigma):\n r'''Calculate Parachor for a pure species, using its density in the\n liquid and gas phases, surface tension, and molecular weight.\n\n .. math::\n P = \\frac{\\sigma^{0.25} MW}{\\rho_L - \\rho_V}\n \n Parameters\n ----------\n MW : float\n Molecular weight, [g/mol]\n rhol : float\n Liquid density [kg/m^3]\n rhog : float\n Gas density [kg/m^3]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n P : float\n Parachor, [N^0.25*m^2.75/mol]\n\n Notes\n -----\n To convert the output of this function to units of [mN^0.25*m^2.75/kmol], \n multiply by 5623.4132519.\n \n Values in group contribution tables for Parachor are often listed as \n dimensionless, in which they are multiplied by 5623413 and the appropriate\n units to make them dimensionless.\n \n Examples\n --------\n Calculating Parachor from a known surface tension for methyl isobutyl \n ketone at 293.15 K\n \n >>> Parachor(100.15888, 800.8088185536124, 4.97865317223119, 0.02672166960656005)\n 5.088443542210164e-05\n \n Converting to the `dimensionless` form:\n \n >>> 5623413*5.088443542210164e-05\n 286.14419565030687\n \n Compared to 274.9 according to a group contribution method described in\n [3]_.\n\n References\n ----------\n .. [1] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n .. [2] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n 8E. McGraw-Hill Professional, 2007.\n .. [3] Danner, Ronald P, and Design Institute for Physical Property Data.\n Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982.\n '''\n rhol, rhog = rhol*1000., rhog*1000. # Convert kg/m^3 to g/m^3\n return sigma**0.25*MW/(rhol-rhog)", "response": "r Returns a Parachor for a pure species with the given mass and gas phases."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef phase_identification_parameter(V, dP_dT, dP_dV, d2P_dV2, d2P_dVdT):\n r'''Calculate the Phase Identification Parameter developed in [1]_ for\n the accurate and efficient determination of whether a fluid is a liquid or\n a gas based on the results of an equation of state. For supercritical \n conditions, this provides a good method for choosing which property \n correlations to use.\n \n .. math::\n \\Pi = V \\left[\\frac{\\frac{\\partial^2 P}{\\partial V \\partial T}}\n {\\frac{\\partial P }{\\partial T}}- \\frac{\\frac{\\partial^2 P}{\\partial \n V^2}}{\\frac{\\partial P}{\\partial V}} \\right]\n\n Parameters\n ----------\n V : float\n Molar volume at `T` and `P`, [m^3/mol]\n dP_dT : float\n Derivative of `P` with respect to `T`, [Pa/K]\n dP_dV : float\n Derivative of `P` with respect to `V`, [Pa*mol/m^3]\n d2P_dV2 : float\n Second derivative of `P` with respect to `V`, [Pa*mol^2/m^6]\n d2P_dVdT : float\n Second derivative of `P` with respect to both `V` and `T`, [Pa*mol/m^3/K]\n\n Returns\n -------\n PIP : float\n Phase Identification Parameter, [-]\n \n Notes\n -----\n Heuristics were used by process simulators before the invent of this \n parameter. \n \n The criteria for liquid is Pi > 1; for vapor, Pi <= 1.\n \n There is also a solid phase mechanism available. For solids, the Solid \n Phase Identification Parameter is greater than 1, like liquids; however, \n unlike liquids, d2P_dVdT is always >0; it is < 0 for liquids and gases.\n\n Examples\n --------\n Calculated for hexane from the PR EOS at 299 K and 1 MPa (liquid):\n \n >>> phase_identification_parameter(0.000130229900874, 582169.397484, \n ... -3.66431747236e+12, 4.48067893805e+17, -20518995218.2)\n 11.33428990564796\n\n References\n ----------\n .. [1] Venkatarathnam, G., and L. R. Oellrich. \"Identification of the Phase\n of a Fluid Using Partial Derivatives of Pressure, Volume, and \n Temperature without Reference to Saturation Properties: Applications in \n Phase Equilibria Calculations.\" Fluid Phase Equilibria 301, no. 2 \n (February 25, 2011): 225-33. doi:10.1016/j.fluid.2010.12.001.\n .. [2] Jayanti, Pranava Chaitanya, and G. Venkatarathnam. \"Identification\n of the Phase of a Substance from the Derivatives of Pressure, Volume and\n Temperature, without Prior Knowledge of Saturation Properties: Extension\n to Solid Phase.\" Fluid Phase Equilibria 425 (October 15, 2016): 269-277.\n doi:10.1016/j.fluid.2016.06.001.\n '''\n return V*(d2P_dVdT/dP_dT - d2P_dV2/dP_dV)", "response": "r Calculates the Phase Identification Parameter for a given fluid."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef phase_identification_parameter_phase(d2P_dVdT, V=None, dP_dT=None, dP_dV=None, d2P_dV2=None):\n r'''Uses the Phase Identification Parameter concept developed in [1]_ and \n [2]_ to determine if a chemical is a solid, liquid, or vapor given the \n appropriate thermodynamic conditions.\n\n The criteria for liquid is PIP > 1; for vapor, PIP <= 1.\n\n For solids, PIP(solid) is defined to be d2P_dVdT. If it is larger than 0, \n the species is a solid. It is less than 0 for all liquids and gases.\n\n Parameters\n ----------\n d2P_dVdT : float\n Second derivative of `P` with respect to both `V` and `T`, [Pa*mol/m^3/K]\n V : float, optional\n Molar volume at `T` and `P`, [m^3/mol]\n dP_dT : float, optional\n Derivative of `P` with respect to `T`, [Pa/K]\n dP_dV : float, optional\n Derivative of `P` with respect to `V`, [Pa*mol/m^3]\n d2P_dV2 : float, optionsl\n Second derivative of `P` with respect to `V`, [Pa*mol^2/m^6]\n\n Returns\n -------\n phase : str\n Either 's', 'l' or 'g'\n \n Notes\n -----\n The criteria for being a solid phase is checked first, which only\n requires d2P_dVdT. All other inputs are optional for this reason.\n However, an exception will be raised if the other inputs become \n needed to determine if a species is a liquid or a gas.\n \n Examples\n --------\n Calculated for hexane from the PR EOS at 299 K and 1 MPa (liquid):\n \n >>> phase_identification_parameter_phase(-20518995218.2, 0.000130229900874, \n ... 582169.397484, -3.66431747236e+12, 4.48067893805e+17)\n 'l'\n\n References\n ----------\n .. [1] Venkatarathnam, G., and L. R. Oellrich. \"Identification of the Phase\n of a Fluid Using Partial Derivatives of Pressure, Volume, and \n Temperature without Reference to Saturation Properties: Applications in \n Phase Equilibria Calculations.\" Fluid Phase Equilibria 301, no. 2 \n (February 25, 2011): 225-33. doi:10.1016/j.fluid.2010.12.001.\n .. [2] Jayanti, Pranava Chaitanya, and G. Venkatarathnam. \"Identification\n of the Phase of a Substance from the Derivatives of Pressure, Volume and\n Temperature, without Prior Knowledge of Saturation Properties: Extension\n to Solid Phase.\" Fluid Phase Equilibria 425 (October 15, 2016): 269-277.\n doi:10.1016/j.fluid.2016.06.001.\n '''\n if d2P_dVdT > 0:\n return 's'\n else:\n PIP = phase_identification_parameter(V=V, dP_dT=dP_dT, dP_dV=dP_dV, \n d2P_dV2=d2P_dV2, d2P_dVdT=d2P_dVdT)\n return 'l' if PIP > 1 else 'g'", "response": "r Returns a new base - order tree for a phase identification parameter."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef speed_of_sound(V, dP_dV, Cp, Cv, MW=None):\n r'''Calculate a real fluid's speed of sound. The required derivatives should \n be calculated with an equation of state, and `Cp` and `Cv` are both the\n real fluid versions. Expression is given in [1]_ and [2]_; a unit conversion\n is further performed to obtain a result in m/s. If MW is not provided the \n result is returned in units of m*kg^0.5/s/mol^0.5.\n\n .. math::\n w = \\left[-V^2 \\left(\\frac{\\partial P}{\\partial V}\\right)_T \\frac{C_p}\n {C_v}\\right]^{1/2}\n \n Parameters\n ----------\n V : float\n Molar volume of fluid, [m^3/mol]\n dP_dV : float\n Derivative of `P` with respect to `V`, [Pa*mol/m^3]\n Cp : float\n Real fluid heat capacity at constant pressure, [J/mol/K]\n Cv : float\n Real fluid heat capacity at constant volume, [J/mol/K]\n MW : float, optional\n Molecular weight, [g/mol]\n\n Returns\n -------\n w : float\n Speed of sound for a real gas, [m/s or m*kg^0.5/s/mol^0.5 or MW missing]\n \n Notes\n -----\n An alternate expression based on molar density is as follows:\n \n .. math::\n w = \\left[\\left(\\frac{\\partial P}{\\partial \\rho}\\right)_T \\frac{C_p}\n {C_v}\\right]^{1/2}\n\n The form with the unit conversion performed inside it is as follows:\n \n .. math::\n w = \\left[-V^2 \\frac{1000}{MW}\\left(\\frac{\\partial P}{\\partial V}\n \\right)_T \\frac{C_p}{C_v}\\right]^{1/2}\n \n Examples\n --------\n Example from [2]_:\n \n >>> speed_of_sound(V=0.00229754, dP_dV=-3.5459e+08, Cp=153.235, Cv=132.435, MW=67.152)\n 179.5868138460819\n\n References\n ----------\n .. [1] Gmehling, Jurgen, Barbel Kolbe, Michael Kleiber, and Jurgen Rarey.\n Chemical Thermodynamics for Process Simulation. 1st edition. Weinheim: \n Wiley-VCH, 2012.\n .. [2] Pratt, R. M. \"Thermodynamic Properties Involving Derivatives: Using \n the Peng-Robinson Equation of State.\" Chemical Engineering Education 35,\n no. 2 (March 1, 2001): 112-115. \n '''\n if not MW:\n return (-V**2*dP_dV*Cp/Cv)**0.5\n else:\n return (-V**2*1000./MW*dP_dV*Cp/Cv)**0.5", "response": "r Calculates a real fluid s speed of sound."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef Z_from_virial_density_form(T, P, *args):\n r'''Calculates the compressibility factor of a gas given its temperature,\n pressure, and molar density-form virial coefficients. Any number of\n coefficients is supported.\n\n .. math::\n Z = \\frac{PV}{RT} = 1 + \\frac{B}{V} + \\frac{C}{V^2} + \\frac{D}{V^3}\n + \\frac{E}{V^4} \\dots\n\n Parameters\n ----------\n T : float\n Temperature, [K]\n P : float\n Pressure, [Pa]\n B to Z : float, optional\n Virial coefficients, [various]\n\n Returns\n -------\n Z : float\n Compressibility factor at T, P, and with given virial coefficients, [-]\n\n Notes\n -----\n For use with B or with B and C or with B and C and D, optimized equations \n are used to obtain the compressibility factor directly.\n If more coefficients are provided, uses numpy's roots function to solve \n this equation. This takes substantially longer as the solution is \n numerical.\n \n If no virial coefficients are given, returns 1, as per the ideal gas law.\n \n The units of each virial coefficient are as follows, where for B, n=1, and\n C, n=2, and so on.\n \n .. math::\n \\left(\\frac{\\text{m}^3}{\\text{mol}}\\right)^n\n\n Examples\n --------\n >>> Z_from_virial_density_form(300, 122057.233762653, 1E-4, 1E-5, 1E-6, 1E-7)\n 1.2843496002100001\n\n References\n ----------\n .. [1] Prausnitz, John M., Rudiger N. Lichtenthaler, and Edmundo Gomes de \n Azevedo. Molecular Thermodynamics of Fluid-Phase Equilibria. 3rd \n edition. Upper Saddle River, N.J: Prentice Hall, 1998.\n .. [2] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n Butterworth-Heinemann, 1985.\n '''\n l = len(args)\n if l == 1:\n return 1/2. + (4*args[0]*P + R*T)**0.5/(2*(R*T)**0.5)\n# return ((R*T*(4*args[0]*P + R*T))**0.5 + R*T)/(2*P)\n if l == 2:\n B, C = args\n # A small imaginary part is ignored\n return (P*(-(3*B*R*T/P + R**2*T**2/P**2)/(3*(-1/2 + csqrt(3)*1j/2)*(-9*B*R**2*T**2/(2*P**2) - 27*C*R*T/(2*P) + csqrt(-4*(3*B*R*T/P + R**2*T**2/P**2)**(3+0j) + (-9*B*R**2*T**2/P**2 - 27*C*R*T/P - 2*R**3*T**3/P**3)**(2+0j))/2 - R**3*T**3/P**3)**(1/3.+0j)) - (-1/2 + csqrt(3)*1j/2)*(-9*B*R**2*T**2/(2*P**2) - 27*C*R*T/(2*P) + csqrt(-4*(3*B*R*T/P + R**2*T**2/P**2)**(3+0j) + (-9*B*R**2*T**2/P**2 - 27*C*R*T/P - 2*R**3*T**3/P**3)**(2+0j))/2 - R**3*T**3/P**3)**(1/3.+0j)/3 + R*T/(3*P))/(R*T)).real\n if l == 3:\n # Huge mess. Ideally sympy could optimize a function for quick python \n # execution. Derived with kate's text highlighting\n B, C, D = args\n P2 = P**2 \n RT = R*T\n BRT = B*RT\n T2 = T**2\n R2 = R**2\n RT23 = 3*R2*T2\n mCRT = -C*RT\n P2256 = 256*P2\n \n RT23P2256 = RT23/(P2256)\n big1 = (D*RT/P - (-BRT/P - RT23/(8*P2))**2/12 - RT*(mCRT/(4*P) - RT*(BRT/(16*P) + RT23P2256)/P)/P)\n big3 = (-BRT/P - RT23/(8*P2))\n big4 = (mCRT/P - RT*(BRT/(2*P) + R2*T2/(8*P2))/P)\n big5 = big3*(-D*RT/P + RT*(mCRT/(4*P) - RT*(BRT/(16*P) + RT23P2256)/P)/P)\n big2 = 2*big1/(3*(big3**3/216 - big5/6 + big4**2/16 + csqrt(big1**3/27 + (-big3**3/108 + big5/3 - big4**2/8)**2/4))**(1/3))\n big7 = 2*BRT/(3*P) - big2 + 2*(big3**3/216 - big5/6 + big4**2/16 + csqrt(big1**3/27 + (-big3**3/108 + big5/3 - big4**2/8)**2/4))**(1/3) + R2*T2/(4*P2)\n return (P*(((csqrt(big7)/2 + csqrt(4*BRT/(3*P) - (-2*C*RT/P - 2*RT*(BRT/(2*P) + R2*T2/(8*P2))/P)/csqrt(big7) + big2 - 2*(big3**3/216 - big5/6 + big4**2/16 + csqrt(big1**3/27 + (-big3**3/108 + big5/3 - big4**2/8)**2/4))**(1/3) + R2*T2/(2*P2))/2 + RT/(4*P))))/R/T).real\n\n args = list(args)\n args.reverse()\n args.extend([1, -P/R/T])\n solns = np.roots(args)\n rho = [i for i in solns if not i.imag and i.real > 0][0].real # Quicker than indexing where imag ==0\n return P/rho/R/T", "response": "r Calculates the compressibility factor at T P with given virial coefficients."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef none_and_length_check(all_inputs, length=None):\n r'''Checks inputs for suitability of use by a mixing rule which requires\n all inputs to be of the same length and non-None. A number of variations\n were attempted for this function; this was found to be the quickest.\n\n Parameters\n ----------\n all_inputs : array-like of array-like\n list of all the lists of inputs, [-]\n length : int, optional\n Length of the desired inputs, [-]\n\n Returns\n -------\n False/True : bool\n Returns True only if all inputs are the same length (or length `length`)\n and none of the inputs contain None [-]\n\n Notes\n -----\n Does not check for nan values.\n\n Examples\n --------\n >>> none_and_length_check(([1, 1], [1, 1], [1, 30], [10,0]), length=2)\n True\n '''\n if not length:\n length = len(all_inputs[0])\n for things in all_inputs:\n if None in things or len(things) != length:\n return False\n return True", "response": "r Checks that all inputs contain None and length."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef allclose_variable(a, b, limits, rtols=None, atols=None):\n '''Returns True if two arrays are element-wise equal within several \n different tolerances. Tolerance values are always positive, usually\n very small. Based on numpy's allclose function.\n \n Only atols or rtols needs to be specified; both are used if given.\n \n Parameters\n ----------\n a, b : array_like\n Input arrays to compare.\n limits : array_like\n Fractions of elements allowed to not match to within each tolerance.\n rtols : array_like\n The relative tolerance parameters.\n atols : float\n The absolute tolerance parameters.\n\n Returns\n -------\n allclose : bool\n Returns True if the two arrays are equal within the given\n tolerances; False otherwise.\n \n Examples\n --------\n 10 random similar variables, all of them matching to within 1E-5, allowing \n up to half to match up to 1E-6.\n \n >>> x = [2.7244322249597719e-08, 3.0105683900110473e-10, 2.7244124924802327e-08, 3.0105259397637556e-10, 2.7243929226310193e-08, 3.0104990272770901e-10, 2.7243666849384451e-08, 3.0104101821236015e-10, 2.7243433745917367e-08, 3.0103707421519949e-10]\n >>> y = [2.7244328304561904e-08, 3.0105753470546008e-10, 2.724412872417824e-08, 3.0105303055834564e-10, 2.7243914341030203e-08, 3.0104819238021998e-10, 2.7243684057561379e-08, 3.0104299541023674e-10, 2.7243436694839306e-08, 3.010374130526363e-10]\n >>> allclose_variable(x, y, limits=[.0, .5], rtols=[1E-5, 1E-6])\n True\n '''\n l = float(len(a))\n if rtols is None and atols is None:\n raise Exception('Either absolute errors or relative errors must be supplied.')\n elif rtols is None:\n rtols = [0 for i in atols]\n elif atols is None:\n atols = [0 for i in rtols]\n \n for atol, rtol, lim in zip(atols, rtols, limits):\n matches = np.count_nonzero(np.isclose(a, b, rtol=rtol, atol=atol))\n if 1-matches/l > lim:\n return False\n return True", "response": "Returns True if two arrays are element - wise equal within several \n different tolerances."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef polylog2(x):\n r'''Simple function to calculate PolyLog(2, x) from ranges 0 <= x <= 1,\n with relative error guaranteed to be < 1E-7 from 0 to 0.99999. This\n is a Pade approximation, with three coefficient sets with splits at 0.7 \n and 0.99. An exception is raised if x is under 0 or above 1. \n \n\n Parameters\n ----------\n x : float\n Value to evaluate PolyLog(2, x) T\n\n Returns\n -------\n y : float\n Evaluated result\n\n Notes\n -----\n Efficient (2-4 microseconds). No implementation of this function exists in \n SciPy. Derived with mpmath's pade approximation.\n Required for the entropy integral of \n :obj:`thermo.heat_capacity.Zabransky_quasi_polynomial`.\n\n Examples\n --------\n >>> polylog2(0.5)\n 0.5822405264516294\n '''\n if 0 <= x <= 0.7:\n p = [0.06184590404457956, -0.7460693871557973, 2.2435704485433376, -2.1944070385048526, 0.3382265629285811, 0.2791966558569478]\n q = [-0.005308735283483908, 0.1823421262956287, -1.2364596896290079, 2.9897802200092296, -2.9365321202088004, 1.0]\n offset = 0.26\n elif 0.7 < x <= 0.99:\n p = [7543860.817140365, -10254250.429758755, -4186383.973408412, 7724476.972409749, -3130743.609030545, 600806.068543299, -62981.15051292659, 3696.7937385473397, -114.06795167646395, 1.4406337969700391]\n q = [-1262997.3422452002, 10684514.56076485, -16931658.916668657, 10275996.02842749, -3079141.9506451315, 511164.4690136096, -49254.56172495263, 2738.0399260270983, -81.36790509581284, 1.0]\n offset = 0.95\n elif 0.99 < x <= 1:\n p = [8.548256176424551e+34, 1.8485781239087334e+35, -2.1706889553798647e+34, 8.318563643438321e+32, -1.559802348661511e+31, 1.698939241177209e+29, -1.180285031647229e+27, 5.531049937687143e+24, -1.8085903366375877e+22, 4.203276811951035e+19, -6.98211620300421e+16, 82281997048841.92, -67157299796.61345, 36084814.54808544, -11478.108105137717, 1.6370226052761176]\n q = [-1.9763570499484274e+35, 1.4813997374958851e+35, -1.4773854824041134e+34, 5.38853721252814e+32, -9.882387315028929e+30, 1.0635231532999732e+29, -7.334629044071992e+26, 3.420655574477631e+24, -1.1147787784365177e+22, 2.584530363912858e+19, -4.285376337404043e+16, 50430830490687.56, -41115254924.43107, 22072284.971253656, -7015.799744041691, 1.0]\n offset = 0.999\n else:\n raise Exception('Approximation is valid between 0 and 1 only.')\n x = x - offset\n return horner(p, x)/horner(q, x)", "response": "Simple function to calculate the polylog of a single integer."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef mixing_simple(fracs, props):\n r'''Simple function calculates a property based on weighted averages of\n properties. Weights could be mole fractions, volume fractions, mass\n fractions, or anything else.\n\n .. math::\n y = \\sum_i \\text{frac}_i \\cdot \\text{prop}_i\n\n Parameters\n ----------\n fracs : array-like\n Fractions of a mixture\n props: array-like\n Properties\n\n Returns\n -------\n prop : value\n Calculated property\n\n Notes\n -----\n Returns None if any fractions or properties are missing or are not of the\n same length.\n\n Examples\n --------\n >>> mixing_simple([0.1, 0.9], [0.01, 0.02])\n 0.019000000000000003\n '''\n if not none_and_length_check([fracs, props]):\n return None\n result = sum(frac*prop for frac, prop in zip(fracs, props))\n return result", "response": "Simple function calculates a property based on weighted averages of the properties of the mixture."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef mixing_logarithmic(fracs, props):\n r'''Simple function calculates a property based on weighted averages of\n logarithmic properties.\n\n .. math::\n y = \\sum_i \\text{frac}_i \\cdot \\log(\\text{prop}_i)\n\n Parameters\n ----------\n fracs : array-like\n Fractions of a mixture\n props: array-like\n Properties\n\n Returns\n -------\n prop : value\n Calculated property\n\n Notes\n -----\n Does not work on negative values.\n Returns None if any fractions or properties are missing or are not of the\n same length.\n\n Examples\n --------\n >>> mixing_logarithmic([0.1, 0.9], [0.01, 0.02])\n 0.01866065983073615\n '''\n if not none_and_length_check([fracs, props]):\n return None\n return exp(sum(frac*log(prop) for frac, prop in zip(fracs, props)))", "response": "rSimple function calculates a property based on weighted averages of fracs and logarithmic properties."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef phase_select_property(phase=None, s=None, l=None, g=None, V_over_F=None):\n r'''Determines which phase's property should be set as a default, given\n the phase a chemical is, and the property values of various phases. For the\n case of liquid-gas phase, returns None. If the property is not available\n for the current phase, or if the current phase is not known, returns None.\n\n Parameters\n ----------\n phase : str\n One of {'s', 'l', 'g', 'two-phase'}\n s : float\n Solid-phase property\n l : float\n Liquid-phase property\n g : float\n Gas-phase property\n V_over_F : float\n Vapor phase fraction\n\n Returns\n -------\n prop : float\n The selected/calculated property for the relevant phase\n\n Notes\n -----\n Could calculate mole-fraction weighted properties for the two phase regime.\n Could also implement equilibria with solid phases.\n\n Examples\n --------\n >>> phase_select_property(phase='g', l=1560.14, g=3312.)\n 3312.0\n '''\n if phase == 's':\n return s\n elif phase == 'l':\n return l\n elif phase == 'g':\n return g\n elif phase == 'two-phase':\n return None #TODO: all two-phase properties?\n elif phase is None:\n return None\n else:\n raise Exception('Property not recognized')", "response": "r Returns the property that should be used for a given phase."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef set_user_methods(self, user_methods, forced=False):\n r'''Method used to select certain property methods as having a higher\n priority than were set by default. If `forced` is true, then methods\n which were not specified are excluded from consideration.\n\n As a side effect, `method` is removed to ensure than the new methods\n will be used in calculations afterwards.\n\n An exception is raised if any of the methods specified aren't available\n for the chemical. An exception is raised if no methods are provided.\n\n Parameters\n ----------\n user_methods : str or list\n Methods by name to be considered or prefered\n forced : bool, optional\n If True, only the user specified methods will ever be considered;\n if False other methods will be considered if no user methods\n suceed\n '''\n # Accept either a string or a list of methods, and whether\n # or not to only consider the false methods\n if isinstance(user_methods, str):\n user_methods = [user_methods]\n\n # The user's order matters and is retained for use by select_valid_methods\n self.user_methods = user_methods\n self.forced = forced\n\n # Validate that the user's specified methods are actual methods\n if set(self.user_methods).difference(self.all_methods):\n raise Exception(\"One of the given methods is not available for this chemical\")\n if not self.user_methods and self.forced:\n raise Exception('Only user specified methods are considered when forced is True, but no methods were provided')\n\n # Remove previously selected methods\n self.method = None\n self.sorted_valid_methods = []\n self.T_cached = None", "response": "r Sets the methods that are used to select certain property methods for a specific entry in the chemical."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef plot_T_dependent_property(self, Tmin=None, Tmax=None, methods=[],\n pts=50, only_valid=True, order=0): # pragma: no cover\n r'''Method to create a plot of the property vs temperature according to\n either a specified list of methods, or user methods (if set), or all\n methods. User-selectable number of points, and temperature range. If\n only_valid is set,`test_method_validity` will be used to check if each\n temperature in the specified range is valid, and\n `test_property_validity` will be used to test the answer, and the\n method is allowed to fail; only the valid points will be plotted.\n Otherwise, the result will be calculated and displayed as-is. This will\n not suceed if the method fails.\n\n Parameters\n ----------\n Tmin : float\n Minimum temperature, to begin calculating the property, [K]\n Tmax : float\n Maximum temperature, to stop calculating the property, [K]\n methods : list, optional\n List of methods to consider\n pts : int, optional\n A list of points to calculate the property at; if Tmin to Tmax\n covers a wide range of method validities, only a few points may end\n up calculated for a given method so this may need to be large\n only_valid : bool\n If True, only plot successful methods and calculated properties,\n and handle errors; if False, attempt calculation without any\n checking and use methods outside their bounds\n '''\n # This function cannot be tested\n if not has_matplotlib:\n raise Exception('Optional dependency matplotlib is required for plotting')\n if Tmin is None:\n if self.Tmin is not None:\n Tmin = self.Tmin\n else:\n raise Exception('Minimum temperature could not be auto-detected; please provide it')\n if Tmax is None:\n if self.Tmax is not None:\n Tmax = self.Tmax\n else:\n raise Exception('Maximum temperature could not be auto-detected; please provide it')\n\n if not methods:\n if self.user_methods:\n methods = self.user_methods\n else:\n methods = self.all_methods\n Ts = np.linspace(Tmin, Tmax, pts)\n if order == 0:\n for method in methods:\n if only_valid:\n properties, Ts2 = [], []\n for T in Ts:\n if self.test_method_validity(T, method):\n try:\n p = self.calculate(T=T, method=method)\n if self.test_property_validity(p):\n properties.append(p)\n Ts2.append(T)\n except:\n pass\n plt.semilogy(Ts2, properties, label=method)\n else:\n properties = [self.calculate(T=T, method=method) for T in Ts]\n plt.semilogy(Ts, properties, label=method)\n plt.ylabel(self.name + ', ' + self.units)\n plt.title(self.name + ' of ' + self.CASRN)\n elif order > 0:\n for method in methods:\n if only_valid:\n properties, Ts2 = [], []\n for T in Ts:\n if self.test_method_validity(T, method):\n try:\n p = self.calculate_derivative(T=T, method=method, order=order)\n properties.append(p)\n Ts2.append(T)\n except:\n pass\n plt.semilogy(Ts2, properties, label=method)\n else:\n properties = [self.calculate_derivative(T=T, method=method, order=order) for T in Ts]\n plt.semilogy(Ts, properties, label=method)\n plt.ylabel(self.name + ', ' + self.units + '/K^%d derivative of order %d' % (order, order))\n plt.title(self.name + ' derivative of order %d' % order + ' of ' + self.CASRN)\n plt.legend(loc='best')\n plt.xlabel('Temperature, K')\n plt.show()", "response": "Method to create a plot of the property vs temperature for a specific set of methods and temperature range."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef solve_prop(self, goal, reset_method=True):\n r'''Method to solve for the temperature at which a property is at a\n specified value. `T_dependent_property` is used to calculate the value\n of the property as a function of temperature; if `reset_method` is True,\n the best method is used at each temperature as the solver seeks a\n solution. This slows the solution moderately.\n\n Checks the given property value with `test_property_validity` first\n and raises an exception if it is not valid. Requires that Tmin and\n Tmax have been set to know what range to search within.\n\n Search is performed with the brenth solver from SciPy.\n\n Parameters\n ----------\n goal : float\n Propoerty value desired, [`units`]\n reset_method : bool\n Whether or not to reset the method as the solver searches\n\n Returns\n -------\n T : float\n Temperature at which the property is the specified value [K]\n '''\n if self.Tmin is None or self.Tmax is None:\n raise Exception('Both a minimum and a maximum value are not present indicating there is not enough data for temperature dependency.')\n if not self.test_property_validity(goal):\n raise Exception('Input property is not considered plausible; no method would calculate it.')\n\n def error(T):\n if reset_method:\n self.method = None\n return self.T_dependent_property(T) - goal\n try:\n return brenth(error, self.Tmin, self.Tmax)\n except ValueError:\n raise Exception('To within the implemented temperature range, it is not possible to calculate the desired value.')", "response": "r Solve for the temperature at which a property is at a specific value."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef calculate_derivative(self, T, method, order=1):\n r'''Method to calculate a derivative of a property with respect to \n temperature, of a given order using a specified method. Uses SciPy's \n derivative function, with a delta of 1E-6 K and a number of points \n equal to 2*order + 1.\n\n This method can be overwritten by subclasses who may perfer to add\n analytical methods for some or all methods as this is much faster.\n\n If the calculation does not succeed, returns the actual error\n encountered.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the derivative, [K]\n method : str\n Method for which to find the derivative\n order : int\n Order of the derivative, >= 1\n\n Returns\n -------\n derivative : float\n Calculated derivative property, [`units/K^order`]\n '''\n return derivative(self.calculate, T, dx=1e-6, args=[method], n=order, order=1+order*2)", "response": "r Method to calculate a derivative of a property with respect to \n temperature T"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef T_dependent_property_integral(self, T1, T2):\n r'''Method to calculate the integral of a property with respect to\n temperature, using a specified method. Methods found valid by \n `select_valid_methods` are attempted until a method succeeds. If no \n methods are valid and succeed, None is returned.\n \n Calls `calculate_integral` internally to perform the actual\n calculation.\n\n .. math::\n \\text{integral} = \\int_{T_1}^{T_2} \\text{property} \\; dT\n\n Parameters\n ----------\n T1 : float\n Lower limit of integration, [K]\n T2 : float\n Upper limit of integration, [K]\n method : str\n Method for which to find the integral\n\n Returns\n -------\n integral : float\n Calculated integral of the property over the given range, \n [`units*K`]\n '''\n Tavg = 0.5*(T1+T2)\n if self.method:\n # retest within range\n if self.test_method_validity(Tavg, self.method):\n try:\n return self.calculate_integral(T1, T2, self.method)\n except: # pragma: no cover\n pass\n \n sorted_valid_methods = self.select_valid_methods(Tavg)\n for method in sorted_valid_methods:\n try:\n return self.calculate_integral(T1, T2, method)\n except:\n pass\n return None", "response": "r Method to calculate the integral of a property with respect to a specific temperature."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef T_dependent_property_integral_over_T(self, T1, T2):\n r'''Method to calculate the integral of a property over temperature \n with respect to temperature, using a specified method. Methods found\n valid by `select_valid_methods` are attempted until a method succeeds. \n If no methods are valid and succeed, None is returned.\n \n Calls `calculate_integral_over_T` internally to perform the actual\n calculation.\n \n .. math::\n \\text{integral} = \\int_{T_1}^{T_2} \\frac{\\text{property}}{T} \\; dT\n\n Parameters\n ----------\n T1 : float\n Lower limit of integration, [K]\n T2 : float\n Upper limit of integration, [K]\n method : str\n Method for which to find the integral\n\n Returns\n -------\n integral : float\n Calculated integral of the property over the given range, \n [`units`]\n '''\n Tavg = 0.5*(T1+T2)\n if self.method:\n # retest within range\n if self.test_method_validity(Tavg, self.method):\n try:\n return self.calculate_integral_over_T(T1, T2, self.method)\n except: # pragma: no cover\n pass\n \n sorted_valid_methods = self.select_valid_methods(Tavg)\n for method in sorted_valid_methods:\n try:\n return self.calculate_integral_over_T(T1, T2, method)\n except:\n pass\n return None", "response": "r Method to calculate the integral of a property over a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef set_user_methods_P(self, user_methods_P, forced_P=False):\n r'''Method to set the pressure-dependent property methods desired for\n consideration by the user. Can be used to exclude certain methods which\n might have unacceptable accuracy.\n\n As a side effect, the previously selected method is removed when\n this method is called to ensure user methods are tried in the desired\n order.\n\n Parameters\n ----------\n user_methods_P : str or list\n Methods by name to be considered or preferred for pressure effect.\n forced : bool, optional\n If True, only the user specified methods will ever be considered;\n if False other methods will be considered if no user methods\n suceed.\n '''\n # Accept either a string or a list of methods, and whether\n # or not to only consider the false methods\n if isinstance(user_methods_P, str):\n user_methods_P = [user_methods_P]\n\n # The user's order matters and is retained for use by select_valid_methods\n self.user_methods_P = user_methods_P\n self.forced_P = forced_P\n\n # Validate that the user's specified methods are actual methods\n if set(self.user_methods_P).difference(self.all_methods_P):\n raise Exception(\"One of the given methods is not available for this chemical\")\n if not self.user_methods_P and self.forced:\n raise Exception('Only user specified methods are considered when forced is True, but no methods were provided')\n\n # Remove previously selected methods\n self.method_P = None\n self.sorted_valid_methods_P = []\n self.TP_cached = None", "response": "r Method to set the pressure - dependent property methods desired for the user."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef select_valid_methods_P(self, T, P):\n r'''Method to obtain a sorted list methods which are valid at `T`\n according to `test_method_validity`. Considers either only user methods\n if forced is True, or all methods. User methods are first tested\n according to their listed order, and unless forced is True, then all\n methods are tested and sorted by their order in `ranked_methods`.\n\n Parameters\n ----------\n T : float\n Temperature at which to test methods, [K]\n P : float\n Pressure at which to test methods, [Pa]\n\n Returns\n -------\n sorted_valid_methods_P : list\n Sorted lists of methods valid at T and P according to\n `test_method_validity`\n '''\n # Same as select_valid_methods but with _P added to variables\n if self.forced_P:\n considered_methods = list(self.user_methods_P)\n else:\n considered_methods = list(self.all_methods_P)\n\n if self.user_methods_P:\n [considered_methods.remove(i) for i in self.user_methods_P]\n\n preferences = sorted([self.ranked_methods_P.index(i) for i in considered_methods])\n sorted_methods = [self.ranked_methods_P[i] for i in preferences]\n\n if self.user_methods_P:\n [sorted_methods.insert(0, i) for i in reversed(self.user_methods_P)]\n\n sorted_valid_methods_P = []\n for method in sorted_methods:\n if self.test_method_validity_P(T, P, method):\n sorted_valid_methods_P.append(method)\n\n return sorted_valid_methods_P", "response": "r Method to obtain a sorted list of methods which are valid at T and P according to test_method_validity."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef set_tabular_data_P(self, Ts, Ps, properties, name=None, check_properties=True):\n r'''Method to set tabular data to be used for interpolation.\n Ts and Psmust be in increasing order. If no name is given, data will be\n assigned the name 'Tabular data series #x', where x is the number of\n previously added tabular data series. The name is added to all\n methods and is inserted at the start of user methods,\n\n Parameters\n ----------\n Ts : array-like\n Increasing array of temperatures at which properties are specified, [K]\n Ps : array-like\n Increasing array of pressures at which properties are specified, [Pa]\n properties : array-like\n List of properties at Ts, [`units`]\n name : str, optional\n Name assigned to the data\n check_properties : bool\n If True, the properties will be checked for validity with\n `test_property_validity` and raise an exception if any are not\n valid\n '''\n # Ts must be in increasing order.\n if check_properties:\n for p in np.array(properties).ravel():\n if not self.test_property_validity(p):\n raise Exception('One of the properties specified are not feasible')\n if not all(b > a for a, b in zip(Ts, Ts[1:])):\n raise Exception('Temperatures are not sorted in increasing order')\n if not all(b > a for a, b in zip(Ps, Ps[1:])):\n raise Exception('Pressures are not sorted in increasing order')\n\n if name is None:\n name = 'Tabular data series #' + str(len(self.tabular_data)) # Will overwrite a poorly named series\n self.tabular_data[name] = (Ts, Ps, properties)\n\n self.method_P = None\n self.user_methods_P.insert(0, name)\n self.all_methods_P.add(name)\n\n self.set_user_methods_P(user_methods_P=self.user_methods_P, forced_P=self.forced_P)", "response": "r Method to set tabular data for interpolation."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef plot_isotherm(self, T, Pmin=None, Pmax=None, methods_P=[], pts=50,\n only_valid=True): # pragma: no cover\n r'''Method to create a plot of the property vs pressure at a specified\n temperature according to either a specified list of methods, or the \n user methods (if set), or all methods. User-selectable number of \n points, and pressure range. If only_valid is set,\n `test_method_validity_P` will be used to check if each condition in \n the specified range is valid, and `test_property_validity` will be used\n to test the answer, and the method is allowed to fail; only the valid \n points will be plotted. Otherwise, the result will be calculated and \n displayed as-is. This will not suceed if the method fails.\n\n Parameters\n ----------\n T : float\n Temperature at which to create the plot, [K]\n Pmin : float\n Minimum pressure, to begin calculating the property, [Pa]\n Pmax : float\n Maximum pressure, to stop calculating the property, [Pa]\n methods_P : list, optional\n List of methods to consider\n pts : int, optional\n A list of points to calculate the property at; if Pmin to Pmax\n covers a wide range of method validities, only a few points may end\n up calculated for a given method so this may need to be large\n only_valid : bool\n If True, only plot successful methods and calculated properties,\n and handle errors; if False, attempt calculation without any\n checking and use methods outside their bounds\n '''\n # This function cannot be tested\n if not has_matplotlib:\n raise Exception('Optional dependency matplotlib is required for plotting')\n if Pmin is None:\n if self.Pmin is not None:\n Pmin = self.Pmin\n else:\n raise Exception('Minimum pressure could not be auto-detected; please provide it')\n if Pmax is None:\n if self.Pmax is not None:\n Pmax = self.Pmax\n else:\n raise Exception('Maximum pressure could not be auto-detected; please provide it')\n\n if not methods_P:\n if self.user_methods_P:\n methods_P = self.user_methods_P\n else:\n methods_P = self.all_methods_P\n Ps = np.linspace(Pmin, Pmax, pts)\n for method_P in methods_P:\n if only_valid:\n properties, Ps2 = [], []\n for P in Ps:\n if self.test_method_validity_P(T, P, method_P):\n try:\n p = self.calculate_P(T, P, method_P)\n if self.test_property_validity(p):\n properties.append(p)\n Ps2.append(P)\n except:\n pass\n plt.plot(Ps2, properties, label=method_P)\n else:\n properties = [self.calculate_P(T, P, method_P) for P in Ps]\n plt.plot(Ps, properties, label=method_P)\n plt.legend(loc='best')\n plt.ylabel(self.name + ', ' + self.units)\n plt.xlabel('Pressure, Pa')\n plt.title(self.name + ' of ' + self.CASRN)\n plt.show()", "response": "Method to create a plot of the property vs pressure at a specified temperature."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef calculate_derivative_T(self, T, P, method, order=1):\n r'''Method to calculate a derivative of a temperature and pressure\n dependent property with respect to temperature at constant pressure,\n of a given order using a specified method. Uses SciPy's derivative \n function, with a delta of 1E-6 K and a number of points equal to \n 2*order + 1.\n\n This method can be overwritten by subclasses who may perfer to add\n analytical methods for some or all methods as this is much faster.\n\n If the calculation does not succeed, returns the actual error\n encountered.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the derivative, [K]\n P : float\n Pressure at which to calculate the derivative, [Pa]\n method : str\n Method for which to find the derivative\n order : int\n Order of the derivative, >= 1\n\n Returns\n -------\n d_prop_d_T_at_P : float\n Calculated derivative property at constant pressure, \n [`units/K^order`]\n '''\n return derivative(self.calculate_P, T, dx=1e-6, args=[P, method], n=order, order=1+order*2)", "response": "r Method to calculate a derivative of a temperature and pressure at a given constant pressure at a given temperature at a given constant pressure at a given order."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef TP_dependent_property_derivative_T(self, T, P, order=1):\n r'''Method to calculate a derivative of a temperature and pressure\n dependent property with respect to temperature at constant pressure,\n of a given order. Methods found valid by `select_valid_methods_P` are \n attempted until a method succeeds. If no methods are valid and succeed,\n None is returned.\n\n Calls `calculate_derivative_T` internally to perform the actual\n calculation.\n \n .. math::\n \\text{derivative} = \\frac{d (\\text{property})}{d T}|_{P}\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the derivative, [K]\n P : float\n Pressure at which to calculate the derivative, [Pa]\n order : int\n Order of the derivative, >= 1\n\n Returns\n -------\n d_prop_d_T_at_P : float\n Calculated derivative property, [`units/K^order`]\n '''\n sorted_valid_methods_P = self.select_valid_methods_P(T, P)\n for method in sorted_valid_methods_P:\n try:\n return self.calculate_derivative_T(T, P, method, order)\n except:\n pass\n return None", "response": "r Method to calculate a derivative of a temperature and pressure at a given temperature and pressure at a given order."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef TP_dependent_property_derivative_P(self, T, P, order=1):\n r'''Method to calculate a derivative of a temperature and pressure\n dependent property with respect to pressure at constant temperature,\n of a given order. Methods found valid by `select_valid_methods_P` are \n attempted until a method succeeds. If no methods are valid and succeed,\n None is returned.\n\n Calls `calculate_derivative_P` internally to perform the actual\n calculation.\n \n .. math::\n \\text{derivative} = \\frac{d (\\text{property})}{d P}|_{T}\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the derivative, [K]\n P : float\n Pressure at which to calculate the derivative, [Pa]\n order : int\n Order of the derivative, >= 1\n\n Returns\n -------\n d_prop_d_P_at_T : float\n Calculated derivative property, [`units/Pa^order`]\n '''\n sorted_valid_methods_P = self.select_valid_methods_P(T, P)\n for method in sorted_valid_methods_P:\n try:\n return self.calculate_derivative_P(P, T, method, order)\n except:\n pass\n return None", "response": "r Method to calculate a derivative of a temperature and pressure at a given temperature and pressure at constant temperature at a given order."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef mixture_property(self, T, P, zs, ws):\n r'''Method to calculate the property with sanity checking and without\n specifying a specific method. `select_valid_methods` is used to obtain\n a sorted list of methods to try. Methods are then tried in order until\n one succeeds. The methods are allowed to fail, and their results are\n checked with `test_property_validity`. On success, the used method\n is stored in the variable `method`.\n\n If `method` is set, this method is first checked for validity with\n `test_method_validity` for the specified temperature, and if it is\n valid, it is then used to calculate the property. The result is checked\n for validity, and returned if it is valid. If either of the checks fail,\n the function retrieves a full list of valid methods with\n `select_valid_methods` and attempts them as described above.\n\n If no methods are found which succeed, returns None.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the property, [K]\n P : float\n Pressure at which to calculate the property, [Pa]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n\n Returns\n -------\n prop : float\n Calculated property, [`units`]\n '''\n # Optimistic track, with the already set method\n if self.method:\n # retest within range\n if self.test_method_validity(T, P, zs, ws, self.method):\n try:\n prop = self.calculate(T, P, zs, ws, self.method)\n if self.test_property_validity(prop):\n return prop\n except: # pragma: no cover\n pass\n\n # get valid methods at conditions, and try them until one yields a valid\n # property; store the method and return the answer\n self.sorted_valid_methods = self.select_valid_methods(T, P, zs, ws)\n for method in self.sorted_valid_methods:\n try:\n prop = self.calculate(T, P, zs, ws, method)\n if self.test_property_validity(prop):\n self.method = method\n return prop\n except: # pragma: no cover\n pass\n\n # Function returns None if it does not work.\n return None", "response": "r Method to calculate the property of a mixture of properties at a specified temperature and pressure at a specific temperature and temperature and temperature and weight fractions."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef property_derivative_T(self, T, P, zs, ws, order=1):\n r'''Method to calculate a derivative of a mixture property with respect\n to temperature at constant pressure and composition,\n of a given order. Methods found valid by `select_valid_methods` are \n attempted until a method succeeds. If no methods are valid and succeed,\n None is returned.\n\n Calls `calculate_derivative_T` internally to perform the actual\n calculation.\n \n .. math::\n \\text{derivative} = \\frac{d (\\text{property})}{d T}|_{P, z}\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the derivative, [K]\n P : float\n Pressure at which to calculate the derivative, [Pa]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n order : int\n Order of the derivative, >= 1\n\n Returns\n -------\n d_prop_d_T_at_P : float\n Calculated derivative property, [`units/K^order`]\n '''\n sorted_valid_methods = self.select_valid_methods(T, P, zs, ws)\n for method in sorted_valid_methods:\n try:\n return self.calculate_derivative_T(T, P, zs, ws, method, order)\n except:\n pass\n return None", "response": "r Method to calculate a derivative of a mixture property at a given temperature at constant pressure and composition at a given order."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef plot_isotherm(self, T, zs, ws, Pmin=None, Pmax=None, methods=[], pts=50,\n only_valid=True): # pragma: no cover\n r'''Method to create a plot of the property vs pressure at a specified\n temperature and composition according to either a specified list of \n methods, or the user methods (if set), or all methods. User-selectable\n number of points, and pressure range. If only_valid is set,\n `test_method_validity` will be used to check if each condition in \n the specified range is valid, and `test_property_validity` will be used\n to test the answer, and the method is allowed to fail; only the valid \n points will be plotted. Otherwise, the result will be calculated and \n displayed as-is. This will not suceed if the method fails.\n\n Parameters\n ----------\n T : float\n Temperature at which to create the plot, [K]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n Pmin : float\n Minimum pressure, to begin calculating the property, [Pa]\n Pmax : float\n Maximum pressure, to stop calculating the property, [Pa]\n methods : list, optional\n List of methods to consider\n pts : int, optional\n A list of points to calculate the property at; if Pmin to Pmax\n covers a wide range of method validities, only a few points may end\n up calculated for a given method so this may need to be large\n only_valid : bool\n If True, only plot successful methods and calculated properties,\n and handle errors; if False, attempt calculation without any\n checking and use methods outside their bounds\n '''\n # This function cannot be tested\n if not has_matplotlib:\n raise Exception('Optional dependency matplotlib is required for plotting')\n if Pmin is None:\n if self.Pmin is not None:\n Pmin = self.Pmin\n else:\n raise Exception('Minimum pressure could not be auto-detected; please provide it')\n if Pmax is None:\n if self.Pmax is not None:\n Pmax = self.Pmax\n else:\n raise Exception('Maximum pressure could not be auto-detected; please provide it')\n\n if not methods:\n if self.user_methods:\n methods = self.user_methods\n else:\n methods = self.all_methods\n Ps = np.linspace(Pmin, Pmax, pts)\n for method in methods:\n if only_valid:\n properties, Ps2 = [], []\n for P in Ps:\n if self.test_method_validity(T, P, zs, ws, method):\n try:\n p = self.calculate(T, P, zs, ws, method)\n if self.test_property_validity(p):\n properties.append(p)\n Ps2.append(P)\n except:\n pass\n plt.plot(Ps2, properties, label=method)\n else:\n properties = [self.calculate(T, P, zs, ws, method) for P in Ps]\n plt.plot(Ps, properties, label=method)\n plt.legend(loc='best')\n plt.ylabel(self.name + ', ' + self.units)\n plt.xlabel('Pressure, Pa')\n plt.title(self.name + ' of a mixture of ' + ', '.join(self.CASs) \n + ' at mole fractions of ' + ', '.join(str(round(i, 4)) for i in zs) + '.')\n plt.show()", "response": "Method to create a plot of the property vs pressure at a specified temperature and composition."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef refractive_index(CASRN, T=None, AvailableMethods=False, Method=None,\n full_info=True):\n r'''This function handles the retrieval of a chemical's refractive\n index. Lookup is based on CASRNs. Will automatically select a data source\n to use if no Method is provided; returns None if the data is not available.\n\n Function has data for approximately 4500 chemicals.\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n RI : float\n Refractive Index on the Na D line, [-]\n T : float, only returned if full_info == True\n Temperature at which refractive index reading was made\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain RI with the given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n A string for the method name to use, as defined by constants in\n RI_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n RI for the desired chemical, and will return methods instead of RI\n full_info : bool, optional\n If True, function will return the temperature at which the refractive\n index reading was made\n\n Notes\n -----\n Only one source is available in this function. It is:\n\n * 'CRC', a compillation of Organic RI data in [1]_.\n\n Examples\n --------\n >>> refractive_index(CASRN='64-17-5')\n (1.3611, 293.15)\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014.\n '''\n def list_methods():\n methods = []\n if CASRN in CRC_RI_organic.index:\n methods.append(CRC)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == CRC:\n _RI = float(CRC_RI_organic.at[CASRN, 'RI'])\n if full_info:\n _T = float(CRC_RI_organic.at[CASRN, 'RIT'])\n elif Method == NONE:\n _RI, _T = None, None\n else:\n raise Exception('Failure in in function')\n if full_info:\n return _RI, _T\n else:\n return _RI", "response": "r This function handles the retrieval of a refractive index from a given CASRN."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef a_alpha_and_derivatives(self, T, full=True, quick=True):\n r'''Method to calculate `a_alpha` and its first and second\n derivatives for an EOS with the Van der Waals mixing rules. Uses the\n parent class's interface to compute pure component values. Returns\n `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. Calls \n `setup_a_alpha_and_derivatives` before calling\n `a_alpha_and_derivatives` for each species, which typically sets `a` \n and `Tc`. Calls `cleanup_a_alpha_and_derivatives` to remove the set\n properties after the calls are done.\n \n For use in `solve_T` this returns only `a_alpha` if `full` is False.\n \n .. math::\n a \\alpha = \\sum_i \\sum_j z_i z_j {(a\\alpha)}_{ij}\n \n (a\\alpha)_{ij} = (1-k_{ij})\\sqrt{(a\\alpha)_{i}(a\\alpha)_{j}}\n \n Parameters\n ----------\n T : float\n Temperature, [K]\n full : bool, optional\n If False, calculates and returns only `a_alpha`\n quick : bool, optional\n Only the quick variant is implemented; it is little faster anyhow\n \n Returns\n -------\n a_alpha : float\n Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa]\n da_alpha_dT : float\n Temperature derivative of coefficient calculated by EOS-specific \n method, [J^2/mol^2/Pa/K]\n d2a_alpha_dT2 : float\n Second temperature derivative of coefficient calculated by \n EOS-specific method, [J^2/mol^2/Pa/K**2]\n\n Notes\n -----\n The exact expressions can be obtained with the following SymPy \n expression below, commented out for brevity.\n \n >>> from sympy import *\n >>> a_alpha_i, a_alpha_j, kij, T = symbols('a_alpha_i, a_alpha_j, kij, T')\n >>> a_alpha_ij = (1-kij)*sqrt(a_alpha_i(T)*a_alpha_j(T))\n >>> #diff(a_alpha_ij, T)\n >>> #diff(a_alpha_ij, T, T)\n '''\n zs, kijs = self.zs, self.kijs\n a_alphas, da_alpha_dTs, d2a_alpha_dT2s = [], [], []\n \n for i in self.cmps:\n self.setup_a_alpha_and_derivatives(i, T=T)\n # Abuse method resolution order to call the a_alpha_and_derivatives\n # method of the original pure EOS\n # -4 goes back from object, GCEOS, SINGLEPHASEEOS, up to GCEOSMIX\n ds = super(type(self).__mro__[self.a_alpha_mro], self).a_alpha_and_derivatives(T)\n a_alphas.append(ds[0])\n da_alpha_dTs.append(ds[1])\n d2a_alpha_dT2s.append(ds[2])\n self.cleanup_a_alpha_and_derivatives()\n \n da_alpha_dT, d2a_alpha_dT2 = 0.0, 0.0\n \n a_alpha_ijs = [[(1. - kijs[i][j])*(a_alphas[i]*a_alphas[j])**0.5 \n for j in self.cmps] for i in self.cmps]\n \n # Needed in calculation of fugacity coefficients\n a_alpha = sum([a_alpha_ijs[i][j]*zs[i]*zs[j]\n for j in self.cmps for i in self.cmps])\n self.a_alpha_ijs = a_alpha_ijs\n \n if full:\n for i in self.cmps:\n for j in self.cmps:\n a_alphai, a_alphaj = a_alphas[i], a_alphas[j]\n x0 = a_alphai*a_alphaj\n x0_05 = x0**0.5\n zi_zj = zs[i]*zs[j]\n\n da_alpha_dT += zi_zj*((1. - kijs[i][j])/(2.*x0_05)\n *(a_alphai*da_alpha_dTs[j] + a_alphaj*da_alpha_dTs[i]))\n \n x1 = a_alphai*da_alpha_dTs[j]\n x2 = a_alphaj*da_alpha_dTs[i]\n x3 = 2.*a_alphai*da_alpha_dTs[j] + 2.*a_alphaj*da_alpha_dTs[i]\n d2a_alpha_dT2 += (-x0_05*(kijs[i][j] - 1.)*(x0*(\n 2.*a_alphai*d2a_alpha_dT2s[j] + 2.*a_alphaj*d2a_alpha_dT2s[i]\n + 4.*da_alpha_dTs[i]*da_alpha_dTs[j]) - x1*x3 - x2*x3 + (x1 \n + x2)**2)/(4.*x0*x0))*zi_zj\n \n return a_alpha, da_alpha_dT, d2a_alpha_dT2\n else:\n return a_alpha", "response": "Method to calculate a_alpha da_alpha_dT d2a_alpha_dT2 and T for a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef fugacities(self, xs=None, ys=None): \n r'''Helper method for calculating fugacity coefficients for any \n phases present, using either the overall mole fractions for both phases\n or using specified mole fractions for each phase.\n \n Requires `fugacity_coefficients` to be implemented by each subclassing\n EOS.\n \n In addition to setting `fugacities_l` and/or `fugacities_g`, this also\n sets the fugacity coefficients `phis_l` and/or `phis_g`.\n \n .. math::\n \\hat \\phi_i^g = \\frac{\\hat f_i^g}{x_i P}\n \n \\hat \\phi_i^l = \\frac{\\hat f_i^l}{x_i P}\n \n Parameters\n ----------\n xs : list[float], optional\n Liquid-phase mole fractions of each species, [-]\n ys : list[float], optional\n Vapor-phase mole fractions of each species, [-]\n \n Notes\n -----\n It is helpful to check that `fugacity_coefficients` has been\n implemented correctly using the following expression, from [1]_.\n \n .. math::\n \\ln \\hat \\phi_i = \\left[\\frac{\\partial (n\\log \\phi)}{\\partial \n n_i}\\right]_{T,P,n_j,V_t}\n \n For reference, several expressions for fugacity of a component are as\n follows, shown in [1]_ and [2]_.\n \n .. math::\n \\ln \\hat \\phi_i = \\int_{0}^P\\left(\\frac{\\hat V_i}\n {RT} - \\frac{1}{P}\\right)dP\n\n \\ln \\hat \\phi_i = \\int_V^\\infty \\left[\n \\frac{1}{RT}\\frac{\\partial P}{ \\partial n_i}\n - \\frac{1}{V}\\right] d V - \\ln Z\n \n References\n ----------\n .. [1] Hu, Jiawen, Rong Wang, and Shide Mao. \"Some Useful Expressions \n for Deriving Component Fugacity Coefficients from Mixture Fugacity \n Coefficient.\" Fluid Phase Equilibria 268, no. 1-2 (June 25, 2008): \n 7-13. doi:10.1016/j.fluid.2008.03.007.\n .. [2] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n Butterworth-Heinemann, 1985.\n '''\n if self.phase in ['l', 'l/g']:\n if xs is None:\n xs = self.zs\n self.phis_l = self.fugacity_coefficients(self.Z_l, zs=xs)\n self.fugacities_l = [phi*x*self.P for phi, x in zip(self.phis_l, xs)]\n self.lnphis_l = [log(i) for i in self.phis_l]\n if self.phase in ['g', 'l/g']:\n if ys is None:\n ys = self.zs\n self.phis_g = self.fugacity_coefficients(self.Z_g, zs=ys)\n self.fugacities_g = [phi*y*self.P for phi, y in zip(self.phis_g, ys)]\n self.lnphis_g = [log(i) for i in self.phis_g]", "response": "r A method to calculate the fugacity coefficients for any Arc - level entry in the system."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef setup_a_alpha_and_derivatives(self, i, T=None):\n r'''Sets `a`, `kappa`, and `Tc` for a specific component before the \n pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n self.a, self.kappa, self.Tc = self.ais[i], self.kappas[i], self.Tcs[i]", "response": "r Sets a kappa and Tc for a specific species."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef setup_a_alpha_and_derivatives(self, i, T=None):\n r'''Sets `a`, `m`, and `Tc` for a specific component before the \n pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n self.a, self.m, self.Tc = self.ais[i], self.ms[i], self.Tcs[i]", "response": "r Sets a m and Tc for a specific component before the \n pure - species EOS s a_alpha_and_derivatives method is called."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef fugacity_coefficients(self, Z, zs):\n r'''Literature formula for calculating fugacity coefficients for each\n species in a mixture. Verified numerically.\n Called by `fugacities` on initialization, or by a solver routine \n which is performing a flash calculation.\n \n .. math::\n \\ln \\hat \\phi_i = \\frac{b_i}{V-b} - \\ln\\left[Z\\left(1\n - \\frac{b}{V}\\right)\\right] - \\frac{2\\sqrt{aa_i}}{RTV}\n \n Parameters\n ----------\n Z : float\n Compressibility of the mixture for a desired phase, [-]\n zs : list[float], optional\n List of mole factions, either overall or in a specific phase, [-]\n \n Returns\n -------\n phis : float\n Fugacity coefficient for each species, [-]\n \n References\n ----------\n .. [1] Walas, Stanley M. Phase Equilibria in Chemical Engineering. \n Butterworth-Heinemann, 1985.\n '''\n phis = []\n V = Z*R*self.T/self.P\n for i in self.cmps:\n phi = self.bs[i]/(V-self.b) - log(Z*(1. - self.b/V)) - 2.*(self.a_alpha*self.ais[i])**0.5/(R*self.T*V)\n phis.append(exp(phi))\n return phis", "response": "Literature formula for calculating fugacity coefficients for each species in a mixture. Verified numerically. Called by fugacities on initialization and solver routine \n zs is optional and returns a list of lists of fugacity coefficients for each species in a mixture."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef cleanup_a_alpha_and_derivatives(self):\n r'''Removes properties set by `setup_a_alpha_and_derivatives`; run by\n `GCEOSMIX.a_alpha_and_derivatives` after `a_alpha` is calculated for \n every component'''\n del(self.a, self.kappa, self.kappa0, self.kappa1, self.Tc)", "response": "r Removes properties set by setup_a_alpha_and_derivatives after a_alpha is calculated for \n every component"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef setup_a_alpha_and_derivatives(self, i, T=None):\n r'''Sets `a`, `kappa`, `kappa0`, `kappa1`, `kappa2`, `kappa3` and `Tc`\n for a specific component before the \n pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n if not hasattr(self, 'kappas'):\n self.kappas = []\n for Tc, kappa0, kappa1, kappa2, kappa3 in zip(self.Tcs, self.kappa0s, self.kappa1s, self.kappa2s, self.kappa3s):\n Tr = T/Tc\n kappa = kappa0 + ((kappa1 + kappa2*(kappa3 - Tr)*(1. - Tr**0.5))*(1. + Tr**0.5)*(0.7 - Tr))\n self.kappas.append(kappa)\n\n (self.a, self.kappa, self.kappa0, self.kappa1, self.kappa2, \n self.kappa3, self.Tc) = (self.ais[i], self.kappas[i], self.kappa0s[i],\n self.kappa1s[i], self.kappa2s[i], self.kappa3s[i], self.Tcs[i])", "response": "r Sets a and kappa for a specific species EOS."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef cleanup_a_alpha_and_derivatives(self):\n r'''Removes properties set by `setup_a_alpha_and_derivatives`; run by\n `GCEOSMIX.a_alpha_and_derivatives` after `a_alpha` is calculated for \n every component'''\n del(self.a, self.kappa, self.kappa0, self.kappa1, self.kappa2, self.kappa3, self.Tc)", "response": "r Removes properties set by setup_a_alpha_and_derivatives after a_alpha is calculated for \n every component"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef setup_a_alpha_and_derivatives(self, i, T=None):\n r'''Sets `a`, `omega`, and `Tc` for a specific component before the \n pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n self.a, self.Tc, self.omega = self.ais[i], self.Tcs[i], self.omegas[i]", "response": "r Sets a omega Tc and a Tc for a specific component before the \n pure - species EOS s a_alpha_and_derivatives method is called."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef setup_a_alpha_and_derivatives(self, i, T=None):\n r'''Sets `a`, `S1`, `S2` and `Tc` for a specific component before the \n pure-species EOS's `a_alpha_and_derivatives` method is called. Both are \n called by `GCEOSMIX.a_alpha_and_derivatives` for every component.'''\n self.a, self.Tc, self.S1, self.S2 = self.ais[i], self.Tcs[i], self.S1s[i], self.S2s[i]", "response": "r Sets a S1 S2 and Tc for a specific component before the \n pure - species EOS s a_alpha_and_derivatives method is called."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef cleanup_a_alpha_and_derivatives(self):\n r'''Removes properties set by `setup_a_alpha_and_derivatives`; run by\n `GCEOSMIX.a_alpha_and_derivatives` after `a_alpha` is calculated for \n every component'''\n del(self.a, self.Tc, self.S1, self.S2)", "response": "r Removes properties set by setup_a_alpha_and_derivatives after a_alpha is calculated for \n every component"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Nicola_original(T, M, Tc, omega, Hfus):\n r'''Estimates the thermal conductivity of a liquid as a function of\n temperature using the CSP method of Nicola [1]_. A simpler but long\n method claiming high-accuracy and using only statistically significant\n variable following analalysis.\n\n Requires temperature, molecular weight, critical temperature, acentric\n factor and the heat of vaporization.\n\n .. math::\n \\frac{\\lambda}{1 \\text{Wm/K}}=-0.5694-0.1436T_r+5.4893\\times10^{-10}\n \\frac{\\Delta_{fus}H}{\\text{kmol/J}}+0.0508\\omega +\n \\left(\\frac{1 \\text{kg/kmol}}{MW}\\right)^{0.0622}\n\n Parameters\n ----------\n T : float\n Temperature of the fluid [K]\n M : float\n Molecular weight of the fluid [g/mol]\n Tc : float\n Critical temperature of the fluid [K]\n omega : float\n Acentric factor of the fluid [-]\n Hfus : float\n Heat of fusion of the fluid [J/mol]\n\n Returns\n -------\n kl : float\n Estimated liquid thermal conductivity [W/m/k]\n\n Notes\n -----\n A weird statistical correlation. Recent and yet to be reviewed.\n This correlation has been superceded by the author's later work.\n Hfus is internally converted to be in J/kmol.\n\n Examples\n --------\n >>> Nicola_original(300, 142.3, 611.7, 0.49, 201853)\n 0.2305018632230984\n\n References\n ----------\n .. [1] Nicola, Giovanni Di, Eleonora Ciarrocchi, Mariano Pierantozzi, and\n Roman Stryjek. \"A New Equation for the Thermal Conductivity of Organic\n Compounds.\" Journal of Thermal Analysis and Calorimetry 116, no. 1\n (April 1, 2014): 135-40. doi:10.1007/s10973-013-3422-7\n '''\n Tr = T/Tc\n Hfus = Hfus*1000\n return -0.5694 - 0.1436*Tr + 5.4893E-10*Hfus + 0.0508*omega + (1./M)**0.0622", "response": "A function of Nicola s original thermal conductivity of a liquid."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Nicola(T, M, Tc, Pc, omega):\n r'''Estimates the thermal conductivity of a liquid as a function of\n temperature using the CSP method of [1]_. A statistically derived\n equation using any correlated terms.\n\n Requires temperature, molecular weight, critical temperature and pressure,\n and acentric factor.\n\n .. math::\n \\frac{\\lambda}{0.5147 W/m/K} = -0.2537T_r+\\frac{0.0017Pc}{\\text{bar}}\n +0.1501 \\omega + \\left(\\frac{1}{MW}\\right)^{-0.2999}\n\n Parameters\n ----------\n T : float\n Temperature of the fluid [K]\n M : float\n Molecular weight of the fluid [g/mol]\n Tc : float\n Critical temperature of the fluid [K]\n Pc : float\n Critical pressure of the fluid [Pa]\n omega : float\n Acentric factor of the fluid [-]\n\n Returns\n -------\n kl : float\n Estimated liquid thermal conductivity [W/m/k]\n\n Notes\n -----\n A statistical correlation. A revision of an original correlation.\n\n Examples\n --------\n >>> Nicola(300, 142.3, 611.7, 2110000.0, 0.49)\n 0.10863821554584034\n\n References\n ----------\n .. [1] Di Nicola, Giovanni, Eleonora Ciarrocchi, Gianluca Coccia, and\n Mariano Pierantozzi. \"Correlations of Thermal Conductivity for\n Liquid Refrigerants at Atmospheric Pressure or near Saturation.\"\n International Journal of Refrigeration. 2014.\n doi:10.1016/j.ijrefrig.2014.06.003\n '''\n Tr = T/Tc\n Pc = Pc/1E5\n return 0.5147*(-0.2537*Tr + 0.0017*Pc + 0.1501*omega + (1./M)**0.2999)", "response": "r Estimates the thermal conductivity of a liquid in a statistically derived system."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Bahadori_liquid(T, M):\n r'''Estimates the thermal conductivity of parafin liquid hydrocarbons.\n Fits their data well, and is useful as only MW is required.\n X is the Molecular weight, and Y the temperature.\n\n .. math::\n K = a + bY + CY^2 + dY^3\n\n a = A_1 + B_1 X + C_1 X^2 + D_1 X^3\n\n b = A_2 + B_2 X + C_2 X^2 + D_2 X^3\n\n c = A_3 + B_3 X + C_3 X^2 + D_3 X^3\n\n d = A_4 + B_4 X + C_4 X^2 + D_4 X^3\n\n Parameters\n ----------\n T : float\n Temperature of the fluid [K]\n M : float\n Molecular weight of the fluid [g/mol]\n\n Returns\n -------\n kl : float\n Estimated liquid thermal conductivity [W/m/k]\n\n Notes\n -----\n The accuracy of this equation has not been reviewed.\n\n Examples\n --------\n Data point from [1]_.\n\n >>> Bahadori_liquid(273.15, 170)\n 0.14274278108272603\n\n References\n ----------\n .. [1] Bahadori, Alireza, and Saeid Mokhatab. \"Estimating Thermal\n Conductivity of Hydrocarbons.\" Chemical Engineering 115, no. 13\n (December 2008): 52-54\n '''\n A = [-6.48326E-2, 2.715015E-3, -1.08580E-5, 9.853917E-9]\n B = [1.565612E-2, -1.55833E-4, 5.051114E-7, -4.68030E-10]\n C = [-1.80304E-4, 1.758693E-6, -5.55224E-9, 5.201365E-12]\n D = [5.880443E-7, -5.65898E-9, 1.764384E-11, -1.65944E-14]\n X, Y = M, T\n a = A[0] + B[0]*X + C[0]*X**2 + D[0]*X**3\n b = A[1] + B[1]*X + C[1]*X**2 + D[1]*X**3\n c = A[2] + B[2]*X + C[2]*X**2 + D[2]*X**3\n d = A[3] + B[3]*X + C[3]*X**2 + D[3]*X**3\n return a + b*Y + c*Y**2 + d*Y**3", "response": "r Bahadori - Alireza and Saeid Mokhatab."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Missenard(T, P, Tc, Pc, kl):\n r'''Adjustes for pressure the thermal conductivity of a liquid using an\n emperical formula based on [1]_, but as given in [2]_.\n\n .. math::\n \\frac{k}{k^*} = 1 + Q P_r^{0.7}\n\n Parameters\n ----------\n T : float\n Temperature of fluid [K]\n P : float\n Pressure of fluid [Pa]\n Tc: float\n Critical point of fluid [K]\n Pc : float\n Critical pressure of the fluid [Pa]\n kl : float\n Thermal conductivity of liquid at 1 atm or saturation, [W/m/K]\n\n Returns\n -------\n kl_dense : float\n Thermal conductivity of liquid at P, [W/m/K]\n\n Notes\n -----\n This equation is entirely dimensionless; all dimensions cancel.\n An interpolation routine is used here from tabulated values of Q.\n The original source has not been reviewed.\n\n Examples\n --------\n Example from [2]_, toluene; matches.\n\n >>> Missenard(304., 6330E5, 591.8, 41E5, 0.129)\n 0.2198375777069657\n\n References\n ----------\n .. [1] Missenard, F. A., Thermal Conductivity of Organic Liquids of a\n Series or a Group of Liquids , Rev. Gen.Thermodyn., 101 649 (1970).\n .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n '''\n Tr = T/Tc\n Pr = P/Pc\n Q = float(Qfunc_Missenard(Pr, Tr))\n return kl*(1. + Q*Pr**0.7)", "response": "r Missenard is a simple formula that calculates the thermal conductivity of a liquid at a given temperature at a given pressure at a given temperature at a given critical point."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef DIPPR9H(ws, ks):\n r'''Calculates thermal conductivity of a liquid mixture according to\n mixing rules in [1]_ and also in [2]_.\n\n .. math::\n \\lambda_m = \\left( \\sum_i w_i \\lambda_i^{-2}\\right)^{-1/2}\n\n Parameters\n ----------\n ws : float\n Mass fractions of components\n ks : float\n Liquid thermal conductivites of all components, [W/m/K]\n\n Returns\n -------\n kl : float\n Thermal conductivity of liquid mixture, [W/m/K]\n\n Notes\n -----\n This equation is entirely dimensionless; all dimensions cancel.\n The example is from [2]_; all results agree.\n The original source has not been reviewed.\n\n DIPPR Procedure 9H: Method for the Thermal Conductivity of Nonaqueous Liquid Mixtures\n\n Average deviations of 3%. for 118 nonaqueous systems with 817 data points.\n Max deviation 20%. According to DIPPR.\n\n Examples\n --------\n >>> DIPPR9H([0.258, 0.742], [0.1692, 0.1528])\n 0.15657104706719646\n\n References\n ----------\n .. [1] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E. The\n Properties of Gases and Liquids. McGraw-Hill Companies, 1987.\n .. [2] Danner, Ronald P, and Design Institute for Physical Property Data.\n Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982.\n '''\n if not none_and_length_check([ks, ws]): # check same-length inputs\n raise Exception('Function inputs are incorrect format')\n return sum(ws[i]/ks[i]**2 for i in range(len(ws)))**(-0.5)", "response": "r A function that calculates the thermal conductivity of a liquid mixture according to the DIPPR9H formula."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef eli_hanley(T, MW, Tc, Vc, Zc, omega, Cvm):\n r'''Estimates the thermal conductivity of a gas as a function of\n temperature using the reference fluid method of Eli and Hanley [1]_ as\n shown in [2]_.\n\n .. math::\n \\lambda = \\lambda^* + \\frac{\\eta^*}{MW}(1.32)\\left(C_v - \\frac{3R}{2}\\right)\n\n Tr = \\text{min}(Tr, 2)\n\n \\theta = 1 + (\\omega-0.011)\\left(0.56553 - 0.86276\\ln Tr - \\frac{0.69852}{Tr}\\right)\n\n \\psi = [1 + (\\omega - 0.011)(0.38560 - 1.1617\\ln Tr)]\\frac{0.288}{Z_c}\n\n f = \\frac{T_c}{190.4}\\theta\n\n h = \\frac{V_c}{9.92E-5}\\psi\n\n T_0 = T/f\n\n \\eta_0^*(T_0)= \\sum_{n=1}^9 C_n T_0^{(n-4)/3}\n\n \\theta_0 = 1944 \\eta_0\n\n \\lambda^* = \\lambda_0 H\n\n \\eta^* = \\eta^*_0 H \\frac{MW}{16.04}\n\n H = \\left(\\frac{16.04}{MW}\\right)^{0.5}f^{0.5}/h^{2/3}\n\n Parameters\n ----------\n T : float\n Temperature of the gas [K]\n MW : float\n Molecular weight of the gas [g/mol]\n Tc : float\n Critical temperature of the gas [K]\n Vc : float\n Critical volume of the gas [m^3/mol]\n Zc : float\n Critical compressibility of the gas []\n omega : float\n Acentric factor of the gas [-]\n Cvm : float\n Molar contant volume heat capacity of the gas [J/mol/K]\n\n Returns\n -------\n kg : float\n Estimated gas thermal conductivity [W/m/k]\n\n Notes\n -----\n Reference fluid is Methane.\n MW internally converted to kg/g-mol.\n\n Examples\n --------\n 2-methylbutane at low pressure, 373.15 K. Mathes calculation in [2]_.\n\n >>> eli_hanley(T=373.15, MW=72.151, Tc=460.4, Vc=3.06E-4, Zc=0.267,\n ... omega=0.227, Cvm=135.9)\n 0.02247951789135337\n\n References\n ----------\n .. [1] Ely, James F., and H. J. M. Hanley. \"Prediction of Transport\n Properties. 2. Thermal Conductivity of Pure Fluids and Mixtures.\"\n Industrial & Engineering Chemistry Fundamentals 22, no. 1 (February 1,\n 1983): 90-97. doi:10.1021/i100009a016.\n .. [2] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E.\n Properties of Gases and Liquids. McGraw-Hill Companies, 1987.\n '''\n Cs = [2.907741307E6, -3.312874033E6, 1.608101838E6, -4.331904871E5, \n 7.062481330E4, -7.116620750E3, 4.325174400E2, -1.445911210E1, 2.037119479E-1]\n\n Tr = T/Tc\n if Tr > 2: Tr = 2\n theta = 1 + (omega - 0.011)*(0.56553 - 0.86276*log(Tr) - 0.69852/Tr)\n psi = (1 + (omega-0.011)*(0.38560 - 1.1617*log(Tr)))*0.288/Zc\n f = Tc/190.4*theta\n h = Vc/9.92E-5*psi\n T0 = T/f\n eta0 = 1E-7*sum([Ci*T0**((i+1. - 4.)/3.) for i, Ci in enumerate(Cs)])\n k0 = 1944*eta0\n\n H = (16.04/MW)**0.5*f**0.5*h**(-2/3.)\n etas = eta0*H*MW/16.04\n ks = k0*H\n return ks + etas/(MW/1000.)*1.32*(Cvm - 1.5*R)", "response": "Estimate the thermal conductivity of a given gas using the reference fluid method of Eli and Hanley."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef Gharagheizi_gas(T, MW, Tb, Pc, omega):\n r'''Estimates the thermal conductivity of a gas as a function of\n temperature using the CSP method of Gharagheizi [1]_. A convoluted\n method claiming high-accuracy and using only statistically significant\n variable following analalysis.\n\n Requires temperature, molecular weight, boiling temperature and critical\n pressure and acentric factor.\n\n .. math::\n k = 7.9505\\times 10^{-4} + 3.989\\times 10^{-5} T\n -5.419\\times 10^-5 M + 3.989\\times 10^{-5} A\n\n A = \\frac{\\left(2\\omega + T - \\frac{(2\\omega + 3.2825)T}{T_b} + 3.2825\\right)}{0.1MP_cT}\n \\times (3.9752\\omega + 0.1 P_c + 1.9876B + 6.5243)^2\n\n\n Parameters\n ----------\n T : float\n Temperature of the fluid [K]\n MW: float\n Molecular weight of the fluid [g/mol]\n Tb : float\n Boiling temperature of the fluid [K]\n Pc : float\n Critical pressure of the fluid [Pa]\n omega : float\n Acentric factor of the fluid [-]\n\n Returns\n -------\n kg : float\n Estimated gas thermal conductivity [W/m/k]\n\n Notes\n -----\n Pressure is internally converted into 10*kPa but author used correlation with\n kPa; overall, errors have been corrected in the presentation of the formula.\n\n This equation was derived with 15927 points and 1574 compounds.\n Example value from [1]_ is the first point in the supportinf info, for CH4.\n\n Examples\n --------\n >>> Gharagheizi_gas(580., 16.04246, 111.66, 4599000.0, 0.0115478000)\n 0.09594861261873211\n\n References\n ----------\n .. [1] Gharagheizi, Farhad, Poorandokht Ilani-Kashkouli, Mehdi Sattari,\n Amir H. Mohammadi, Deresh Ramjugernath, and Dominique Richon.\n \"Development of a General Model for Determination of Thermal\n Conductivity of Liquid Chemical Compounds at Atmospheric Pressure.\"\n AIChE Journal 59, no. 5 (May 1, 2013): 1702-8. doi:10.1002/aic.13938\n '''\n Pc = Pc/1E4\n B = T + (2.*omega + 2.*T - 2.*T*(2.*omega + 3.2825)/Tb + 3.2825)/(2*omega + T - T*(2*omega+3.2825)/Tb + 3.2825) - T*(2*omega+3.2825)/Tb\n A = (2*omega + T - T*(2*omega + 3.2825)/Tb + 3.2825)/(0.1*MW*Pc*T) * (3.9752*omega + 0.1*Pc + 1.9876*B + 6.5243)**2\n return 7.9505E-4 + 3.989E-5*T - 5.419E-5*MW + 3.989E-5*A", "response": "r Estimates the thermal conductivity of a given resource in a given time - domain basis using the CSP method of Gharagheizi."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef Bahadori_gas(T, MW):\n r'''Estimates the thermal conductivity of hydrocarbons gases at low P.\n Fits their data well, and is useful as only MW is required.\n Y is the Molecular weight, and X the temperature.\n\n .. math::\n K = a + bY + CY^2 + dY^3\n\n a = A_1 + B_1 X + C_1 X^2 + D_1 X^3\n\n b = A_2 + B_2 X + C_2 X^2 + D_2 X^3\n\n c = A_3 + B_3 X + C_3 X^2 + D_3 X^3\n\n d = A_4 + B_4 X + C_4 X^2 + D_4 X^3\n\n Parameters\n ----------\n T : float\n Temperature of the gas [K]\n MW : float\n Molecular weight of the gas [g/mol]\n\n Returns\n -------\n kg : float\n Estimated gas thermal conductivity [W/m/k]\n\n Notes\n -----\n The accuracy of this equation has not been reviewed.\n\n Examples\n --------\n >>> Bahadori_gas(40+273.15, 20) # Point from article\n 0.031968165337873326\n\n References\n ----------\n .. [1] Bahadori, Alireza, and Saeid Mokhatab. \"Estimating Thermal\n Conductivity of Hydrocarbons.\" Chemical Engineering 115, no. 13\n (December 2008): 52-54\n '''\n A = [4.3931323468E-1, -3.88001122207E-2, 9.28616040136E-4, -6.57828995724E-6]\n B = [-2.9624238519E-3, 2.67956145820E-4, -6.40171884139E-6, 4.48579040207E-8]\n C = [7.54249790107E-6, -6.46636219509E-7, 1.5124510261E-8, -1.0376480449E-10]\n D = [-6.0988433456E-9, 5.20752132076E-10, -1.19425545729E-11, 8.0136464085E-14]\n X, Y = T, MW\n a = A[0] + B[0]*X + C[0]*X**2 + D[0]*X**3\n b = A[1] + B[1]*X + C[1]*X**2 + D[1]*X**3\n c = A[2] + B[2]*X + C[2]*X**2 + D[2]*X**3\n d = A[3] + B[3]*X + C[3]*X**2 + D[3]*X**3\n return a + b*Y + c*Y**2 + d*Y**3", "response": "r Estimates the thermal conductivity of Hydrocarbons at low P."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef stiel_thodos_dense(T, MW, Tc, Pc, Vc, Zc, Vm, kg):\n r'''Estimates the thermal conductivity of a gas at high pressure as a\n function of temperature using difference method of Stiel and Thodos [1]_\n as shown in [2]_.\n\n if \\rho_r < 0.5:\n\n .. math::\n (\\lambda-\\lambda^\\circ)\\Gamma Z_c^5=1.22\\times 10^{-2} [\\exp(0.535 \\rho_r)-1]\n\n if 0.5 < \\rho_r < 2.0:\n\n .. math::\n (\\lambda-\\lambda^\\circ)\\Gamma Z_c^5=1.22\\times 10^{-2} [\\exp(0.535 \\rho_r)-1]\n\n if 2 < \\rho_r < 2.8:\n\n .. math::\n (\\lambda-\\lambda^\\circ)\\Gamma Z_c^5=1.22\\times 10^{-2} [\\exp(0.535 \\rho_r)-1]\n\n \\Gamma = 210 \\left(\\frac{T_cMW^3}{P_c^4}\\right)^{1/6}\n\n Parameters\n ----------\n T : float\n Temperature of the gas [K]\n MW : float\n Molecular weight of the gas [g/mol]\n Tc : float\n Critical temperature of the gas [K]\n Pc : float\n Critical pressure of the gas [Pa]\n Vc : float\n Critical volume of the gas [m^3/mol]\n Zc : float\n Critical compressibility of the gas [-]\n Vm : float\n Molar volume of the gas at T and P [m^3/mol]\n kg : float\n Low-pressure gas thermal conductivity [W/m/k]\n\n Returns\n -------\n kg : float\n Estimated dense gas thermal conductivity [W/m/k]\n\n Notes\n -----\n Pc is internally converted to bar.\n\n Examples\n --------\n >>> stiel_thodos_dense(T=378.15, MW=44.013, Tc=309.6, Pc=72.4E5,\n ... Vc=97.4E-6, Zc=0.274, Vm=144E-6, kg=2.34E-2)\n 0.041245574404863684\n\n References\n ----------\n .. [1] Stiel, Leonard I., and George Thodos. \"The Thermal Conductivity of\n Nonpolar Substances in the Dense Gaseous and Liquid Regions.\" AIChE\n Journal 10, no. 1 (January 1, 1964): 26-30. doi:10.1002/aic.690100114.\n .. [2] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E.\n Properties of Gases and Liquids. McGraw-Hill Companies, 1987.\n '''\n gamma = 210*(Tc*MW**3./(Pc/1E5)**4)**(1/6.)\n rhor = Vc/Vm\n if rhor < 0.5:\n term = 1.22E-2*(exp(0.535*rhor) - 1.)\n elif rhor < 2:\n term = 1.14E-2*(exp(0.67*rhor) - 1.069)\n else:\n # Technically only up to 2.8\n term = 2.60E-3*(exp(1.155*rhor) + 2.016)\n diff = term/Zc**5/gamma\n kg = kg + diff\n return kg", "response": "r Estimates the thermal conductivity of a given gas at high pressure using difference method of Stiel and Thodos."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef chung_dense(T, MW, Tc, Vc, omega, Cvm, Vm, mu, dipole, association=0):\n r'''Estimates the thermal conductivity of a gas at high pressure as a\n function of temperature using the reference fluid method of\n Chung [1]_ as shown in [2]_.\n\n .. math::\n \\lambda = \\frac{31.2 \\eta^\\circ \\Psi}{M'}(G_2^{-1} + B_6 y)+qB_7y^2T_r^{1/2}G_2\n\n \\Psi = 1 + \\alpha \\left\\{[0.215+0.28288\\alpha-1.061\\beta+0.26665Z]/\n [0.6366+\\beta Z + 1.061 \\alpha \\beta]\\right\\}\n\n \\alpha = \\frac{C_v}{R}-1.5\n\n \\beta = 0.7862-0.7109\\omega + 1.3168\\omega^2\n\n Z=2+10.5T_r^2\n\n q = 3.586\\times 10^{-3} (T_c/M')^{1/2}/V_c^{2/3}\n\n y = \\frac{V_c}{6V}\n\n G_1 = \\frac{1-0.5y}{(1-y)^3}\n\n G_2 = \\frac{(B_1/y)[1-\\exp(-B_4y)]+ B_2G_1\\exp(B_5y) + B_3G_1}\n {B_1B_4 + B_2 + B_3}\n\n B_i = a_i + b_i \\omega + c_i \\mu_r^4 + d_i \\kappa\n\n\n Parameters\n ----------\n T : float\n Temperature of the gas [K]\n MW : float\n Molecular weight of the gas [g/mol]\n Tc : float\n Critical temperature of the gas [K]\n Vc : float\n Critical volume of the gas [m^3/mol]\n omega : float\n Acentric factor of the gas [-]\n Cvm : float\n Molar contant volume heat capacity of the gas [J/mol/K]\n Vm : float\n Molar volume of the gas at T and P [m^3/mol]\n mu : float\n Low-pressure gas viscosity [Pa*S]\n dipole : float\n Dipole moment [debye]\n association : float, optional\n Association factor [-]\n\n Returns\n -------\n kg : float\n Estimated dense gas thermal conductivity [W/m/k]\n\n Notes\n -----\n MW internally converted to kg/g-mol.\n Vm internally converted to mL/mol.\n [1]_ is not the latest form as presented in [1]_.\n Association factor is assumed 0. Relates to the polarity of the gas.\n\n Coefficients as follows:\n ais = [2.4166E+0, -5.0924E-1, 6.6107E+0, 1.4543E+1, 7.9274E-1, -5.8634E+0, 9.1089E+1]\n\n bis = [7.4824E-1, -1.5094E+0, 5.6207E+0, -8.9139E+0, 8.2019E-1, 1.2801E+1, 1.2811E+2]\n\n cis = [-9.1858E-1, -4.9991E+1, 6.4760E+1, -5.6379E+0, -6.9369E-1, 9.5893E+0, -5.4217E+1]\n\n dis = [1.2172E+2, 6.9983E+1, 2.7039E+1, 7.4344E+1, 6.3173E+0, 6.5529E+1, 5.2381E+2]\n\n\n Examples\n --------\n >>> chung_dense(T=473., MW=42.081, Tc=364.9, Vc=184.6E-6, omega=0.142,\n ... Cvm=82.67, Vm=172.1E-6, mu=134E-7, dipole=0.4)\n 0.06160570379787278\n\n References\n ----------\n .. [1] Chung, Ting Horng, Mohammad Ajlan, Lloyd L. Lee, and Kenneth E.\n Starling. \"Generalized Multiparameter Correlation for Nonpolar and Polar\n Fluid Transport Properties.\" Industrial & Engineering Chemistry Research\n 27, no. 4 (April 1, 1988): 671-79. doi:10.1021/ie00076a024.\n .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition.\n New York: McGraw-Hill Professional, 2000.\n '''\n ais = [2.4166E+0, -5.0924E-1, 6.6107E+0, 1.4543E+1, 7.9274E-1, -5.8634E+0, 9.1089E+1]\n bis = [7.4824E-1, -1.5094E+0, 5.6207E+0, -8.9139E+0, 8.2019E-1, 1.2801E+1, 1.2811E+2]\n cis = [-9.1858E-1, -4.9991E+1, 6.4760E+1, -5.6379E+0, -6.9369E-1, 9.5893E+0, -5.4217E+1]\n dis = [1.2172E+2, 6.9983E+1, 2.7039E+1, 7.4344E+1, 6.3173E+0, 6.5529E+1, 5.2381E+2]\n Tr = T/Tc\n mur = 131.3*dipole/(Vc*1E6*Tc)**0.5\n\n # From Chung Method\n alpha = Cvm/R - 1.5\n beta = 0.7862 - 0.7109*omega + 1.3168*omega**2\n Z = 2 + 10.5*(T/Tc)**2\n psi = 1 + alpha*((0.215 + 0.28288*alpha - 1.061*beta + 0.26665*Z)/(0.6366 + beta*Z + 1.061*alpha*beta))\n\n y = Vc/(6*Vm)\n B1, B2, B3, B4, B5, B6, B7 = [ais[i] + bis[i]*omega + cis[i]*mur**4 + dis[i]*association for i in range(7)]\n G1 = (1 - 0.5*y)/(1. - y)**3\n G2 = (B1/y*(1 - exp(-B4*y)) + B2*G1*exp(B5*y) + B3*G1)/(B1*B4 + B2 + B3)\n q = 3.586E-3*(Tc/(MW/1000.))**0.5/(Vc*1E6)**(2/3.)\n return 31.2*mu*psi/(MW/1000.)*(G2**-1 + B6*y) + q*B7*y**2*Tr**0.5*G2", "response": "Chung - Dense Thermal Conductivity of a system in a single phase."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef calculate(self, T, method):\n r'''Method to calculate low-pressure liquid thermal conductivity at\n tempearture `T` with a given method.\n\n This method has no exception handling; see `T_dependent_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature of the liquid, [K]\n method : str\n Name of the method to use\n\n Returns\n -------\n kl : float\n Thermal conductivity of the liquid at T and a low pressure, [W/m/K]\n '''\n if method == SHEFFY_JOHNSON:\n kl = Sheffy_Johnson(T, self.MW, self.Tm)\n elif method == SATO_RIEDEL:\n kl = Sato_Riedel(T, self.MW, self.Tb, self.Tc)\n elif method == GHARAGHEIZI_L:\n kl = Gharagheizi_liquid(T, self.MW, self.Tb, self.Pc, self.omega)\n elif method == NICOLA:\n kl = Nicola(T, self.MW, self.Tc, self.Pc, self.omega)\n elif method == NICOLA_ORIGINAL:\n kl = Nicola_original(T, self.MW, self.Tc, self.omega, self.Hfus)\n elif method == LAKSHMI_PRASAD:\n kl = Lakshmi_Prasad(T, self.MW)\n elif method == BAHADORI_L:\n kl = Bahadori_liquid(T, self.MW)\n elif method == DIPPR_PERRY_8E:\n kl = EQ100(T, *self.Perrys2_315_coeffs)\n elif method == VDI_PPDS:\n kl = horner(self.VDI_PPDS_coeffs, T)\n elif method == COOLPROP:\n kl = CoolProp_T_dependent_property(T, self.CASRN, 'L', 'l')\n elif method in self.tabular_data:\n kl = self.interpolate(T, method)\n return kl", "response": "r This method calculates the low - pressure liquid thermal conductivity at a given temperature at a given method."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef calculate(self, T, P, zs, ws, method):\n r'''Method to calculate thermal conductivity of a liquid mixture at \n temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n `ws` with a given method.\n\n This method has no exception handling; see `mixture_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the property, [K]\n P : float\n Pressure at which to calculate the property, [Pa]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n method : str\n Name of the method to use\n\n Returns\n -------\n k : float\n Thermal conductivity of the liquid mixture, [W/m/K]\n '''\n if method == SIMPLE:\n ks = [i(T, P) for i in self.ThermalConductivityLiquids]\n return mixing_simple(zs, ks)\n elif method == DIPPR_9H:\n ks = [i(T, P) for i in self.ThermalConductivityLiquids]\n return DIPPR9H(ws, ks)\n elif method == FILIPPOV:\n ks = [i(T, P) for i in self.ThermalConductivityLiquids]\n return Filippov(ws, ks)\n elif method == MAGOMEDOV:\n k_w = self.ThermalConductivityLiquids[self.index_w](T, P)\n ws = list(ws) ; ws.pop(self.index_w)\n return thermal_conductivity_Magomedov(T, P, ws, self.wCASs, k_w)\n else:\n raise Exception('Method not valid')", "response": "r Calculates the thermal conductivity of a liquid mixture at \n temperature pressure mole fractions and weight fractions of all species in the mixture at \n zs and ws."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef load_all_methods(self):\n r'''Method which picks out coefficients for the specified chemical\n from the various dictionaries and DataFrames storing it. All data is\n stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`,\n :obj:`all_methods` and obj:`all_methods_P` as a set of methods for\n which the data exists for.\n\n Called on initialization only. See the source code for the variables at\n which the coefficients are stored. The coefficients can safely be\n altered once the class is initialized. This method can be called again\n to reset the parameters.\n '''\n methods, methods_P = [], []\n Tmins, Tmaxs = [], []\n if self.CASRN in _VDISaturationDict:\n methods.append(VDI_TABULAR)\n Ts, props = VDI_tabular_data(self.CASRN, 'K (g)')\n self.VDI_Tmin = Ts[0]\n self.VDI_Tmax = Ts[-1]\n self.tabular_data[VDI_TABULAR] = (Ts, props)\n Tmins.append(self.VDI_Tmin); Tmaxs.append(self.VDI_Tmax)\n if has_CoolProp and self.CASRN in coolprop_dict:\n methods.append(COOLPROP); methods_P.append(COOLPROP)\n self.CP_f = coolprop_fluids[self.CASRN]\n Tmins.append(self.CP_f.Tmin); Tmaxs.append(self.CP_f.Tc)\n if self.CASRN in Perrys2_314.index:\n methods.append(DIPPR_PERRY_8E)\n _, C1, C2, C3, C4, self.Perrys2_314_Tmin, self.Perrys2_314_Tmax = _Perrys2_314_values[Perrys2_314.index.get_loc(self.CASRN)].tolist()\n self.Perrys2_314_coeffs = [C1, C2, C3, C4]\n Tmins.append(self.Perrys2_314_Tmin); Tmaxs.append(self.Perrys2_314_Tmax)\n if self.CASRN in VDI_PPDS_10.index:\n _, A, B, C, D, E = _VDI_PPDS_10_values[VDI_PPDS_10.index.get_loc(self.CASRN)].tolist()\n self.VDI_PPDS_coeffs = [A, B, C, D, E]\n self.VDI_PPDS_coeffs.reverse()\n methods.append(VDI_PPDS)\n if all((self.MW, self.Tb, self.Pc, self.omega)):\n methods.append(GHARAGHEIZI_G)\n # Turns negative at low T; do not set Tmin\n Tmaxs.append(3000)\n if all((self.Cvgm, self.mug, self.MW, self.Tc)):\n methods.append(DIPPR_9B)\n Tmins.append(0.01); Tmaxs.append(1E4) # No limit here\n if all((self.Cvgm, self.mug, self.MW, self.Tc, self.omega)):\n methods.append(CHUNG)\n Tmins.append(0.01); Tmaxs.append(1E4) # No limit\n if all((self.Cvgm, self.MW, self.Tc, self.Vc, self.Zc, self.omega)):\n methods.append(ELI_HANLEY)\n Tmaxs.append(1E4) # Numeric error at low T\n if all((self.Cvgm, self.mug, self.MW)):\n methods.append(EUCKEN_MOD)\n methods.append(EUCKEN)\n Tmins.append(0.01); Tmaxs.append(1E4) # No limits\n if self.MW:\n methods.append(BAHADORI_G)\n # Terrible method, so don't set methods\n if all([self.MW, self.Tc, self.Vc, self.Zc, self.omega]):\n methods_P.append(ELI_HANLEY_DENSE)\n if all([self.MW, self.Tc, self.Vc, self.omega, self.dipole]):\n methods_P.append(CHUNG_DENSE)\n if all([self.MW, self.Tc, self.Pc, self.Vc, self.Zc]):\n methods_P.append(STIEL_THODOS_DENSE)\n self.all_methods = set(methods)\n self.all_methods_P = set(methods_P)\n if Tmins and Tmaxs:\n self.Tmin, self.Tmax = min(Tmins), max(Tmaxs)", "response": "r This method loads all methods for the specified chemicalicalCOOKIE."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef calculate(self, T, method):\n r'''Method to calculate low-pressure gas thermal conductivity at\n tempearture `T` with a given method.\n\n This method has no exception handling; see `T_dependent_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature of the gas, [K]\n method : str\n Name of the method to use\n\n Returns\n -------\n kg : float\n Thermal conductivity of the gas at T and a low pressure, [W/m/K]\n '''\n if method == GHARAGHEIZI_G:\n kg = Gharagheizi_gas(T, self.MW, self.Tb, self.Pc, self.omega)\n elif method == DIPPR_9B:\n Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n kg = DIPPR9B(T, self.MW, Cvgm, mug, self.Tc)\n elif method == CHUNG:\n Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n kg = Chung(T, self.MW, self.Tc, self.omega, Cvgm, mug)\n elif method == ELI_HANLEY:\n Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n kg = eli_hanley(T, self.MW, self.Tc, self.Vc, self.Zc, self.omega, Cvgm)\n elif method == EUCKEN_MOD:\n Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n kg = Eucken_modified(self.MW, Cvgm, mug)\n elif method == EUCKEN:\n Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm\n mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug\n kg = Eucken(self.MW, Cvgm, mug)\n elif method == DIPPR_PERRY_8E:\n kg = EQ102(T, *self.Perrys2_314_coeffs)\n elif method == VDI_PPDS:\n kg = horner(self.VDI_PPDS_coeffs, T)\n elif method == BAHADORI_G:\n kg = Bahadori_gas(T, self.MW)\n elif method == COOLPROP:\n kg = CoolProp_T_dependent_property(T, self.CASRN, 'L', 'g')\n elif method in self.tabular_data:\n kg = self.interpolate(T, method)\n return kg", "response": "r Method to calculate the low - pressure thermal conductivity at a given temperature."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef calculate(self, T, P, zs, ws, method):\n r'''Method to calculate thermal conductivity of a gas mixture at \n temperature `T`, pressure `P`, mole fractions `zs` and weight fractions\n `ws` with a given method.\n\n This method has no exception handling; see `mixture_property`\n for that.\n\n Parameters\n ----------\n T : float\n Temperature at which to calculate the property, [K]\n P : float\n Pressure at which to calculate the property, [Pa]\n zs : list[float]\n Mole fractions of all species in the mixture, [-]\n ws : list[float]\n Weight fractions of all species in the mixture, [-]\n method : str\n Name of the method to use\n\n Returns\n -------\n kg : float\n Thermal conductivity of gas mixture, [W/m/K]\n '''\n if method == SIMPLE:\n ks = [i(T, P) for i in self.ThermalConductivityGases]\n return mixing_simple(zs, ks)\n elif method == LINDSAY_BROMLEY:\n ks = [i(T, P) for i in self.ThermalConductivityGases]\n mus = [i(T, P) for i in self.ViscosityGases]\n return Lindsay_Bromley(T=T, ys=zs, ks=ks, mus=mus, Tbs=self.Tbs, MWs=self.MWs)\n else:\n raise Exception('Method not valid')", "response": "Method to calculate thermal conductivity of a gas mixture at \n temperature pressure mole fractions and weight fractions of all species in the mixture at these times."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef atom_fractions(atoms):\n r'''Calculates the atomic fractions of each element in a compound,\n given a dictionary of its atoms and their counts, in the format\n {symbol: count}.\n\n .. math::\n a_i = \\frac{n_i}{\\sum_i n_i}\n\n Parameters\n ----------\n atoms : dict\n dictionary of counts of individual atoms, indexed by symbol with\n proper capitalization, [-]\n\n Returns\n -------\n afracs : dict\n dictionary of atomic fractions of individual atoms, indexed by symbol\n with proper capitalization, [-]\n\n Notes\n -----\n No actual data on the elements is used, so incorrect or custom compounds\n would not raise an error.\n\n Examples\n --------\n >>> atom_fractions({'H': 12, 'C': 20, 'O': 5})\n {'H': 0.32432432432432434, 'C': 0.5405405405405406, 'O': 0.13513513513513514}\n\n References\n ----------\n .. [1] RDKit: Open-source cheminformatics; http://www.rdkit.org\n '''\n count = sum(atoms.values())\n afracs = {}\n for i in atoms:\n afracs[i] = atoms[i]/count\n return afracs", "response": "r Returns the atomic fractions of each element in a compound."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef similarity_variable(atoms, MW=None):\n r'''Calculates the similarity variable of an compound, as defined in [1]_.\n Currently only applied for certain heat capacity estimation routines.\n\n .. math::\n \\alpha = \\frac{N}{MW} = \\frac{\\sum_i n_i}{\\sum_i n_i MW_i}\n\n Parameters\n ----------\n atoms : dict\n dictionary of counts of individual atoms, indexed by symbol with\n proper capitalization, [-]\n MW : float, optional\n Molecular weight, [g/mol]\n\n Returns\n -------\n similarity_variable : float\n Similarity variable as defined in [1]_, [mol/g]\n\n Notes\n -----\n Molecular weight is optional, but speeds up the calculation slightly. It\n is calculated using the function `molecular_weight` if not specified.\n\n Examples\n --------\n >>> similarity_variable({'H': 32, 'C': 15})\n 0.2212654140784498\n\n References\n ----------\n .. [1] La\u0161tovka, V\u00e1clav, Nasser Sallamie, and John M. Shaw. \"A Similarity\n Variable for Estimating the Heat Capacity of Solid Organic Compounds:\n Part I. Fundamentals.\" Fluid Phase Equilibria 268, no. 1-2\n (June 25, 2008): 51-60. doi:10.1016/j.fluid.2008.03.019.\n '''\n if not MW:\n MW = molecular_weight(atoms)\n return sum(atoms.values())/MW", "response": "r Calculates the similarity variable of an object."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef simple_formula_parser(formula):\n r'''Basic formula parser, primarily for obtaining element counts from \n formulas as formated in PubChem. Handles formulas with integer counts, \n but no brackets, no hydrates, no charges, no isotopes, and no group\n multipliers.\n \n Strips charges from the end of a formula first. Accepts repeated chemical\n units. Performs no sanity checking that elements are actually elements.\n As it uses regular expressions for matching, errors are mostly just ignored.\n \n Parameters\n ----------\n formula : str\n Formula string, very simply formats only.\n\n Returns\n -------\n atoms : dict\n dictionary of counts of individual atoms, indexed by symbol with\n proper capitalization, [-]\n\n Notes\n -----\n Inspiration taken from the thermopyl project, at\n https://github.com/choderalab/thermopyl.\n\n Examples\n --------\n >>> simple_formula_parser('CO2')\n {'C': 1, 'O': 2}\n '''\n formula = formula.split('+')[0].split('-')[0]\n groups = _formula_p1.split(formula)[1::2]\n cnt = Counter()\n for group in groups:\n ele, count = _formula_p2.split(group)[1:]\n cnt[ele] += int(count) if count.isdigit() else 1\n return dict(cnt)", "response": "Basic formula parser primarily for obtaining element counts from a single formula."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef nested_formula_parser(formula, check=True):\n r'''Improved formula parser which handles braces and their multipliers, \n as well as rational element counts.\n\n Strips charges from the end of a formula first. Accepts repeated chemical\n units. Performs no sanity checking that elements are actually elements.\n As it uses regular expressions for matching, errors are mostly just ignored.\n \n Parameters\n ----------\n formula : str\n Formula string, very simply formats only.\n check : bool\n If `check` is True, a simple check will be performed to determine if\n a formula is not a formula and an exception will be raised if it is\n not, [-]\n\n Returns\n -------\n atoms : dict\n dictionary of counts of individual atoms, indexed by symbol with\n proper capitalization, [-]\n\n Notes\n -----\n Inspired by the approach taken by CrazyMerlyn on a reddit DailyProgrammer\n challenge, at https://www.reddit.com/r/dailyprogrammer/comments/6eerfk/20170531_challenge_317_intermediate_counting/\n\n Examples\n --------\n >>> pprint(nested_formula_parser('Pd(NH3)4.0001+2'))\n {'H': 12.0003, 'N': 4.0001, 'Pd': 1}\n '''\n formula = formula.replace('[', '').replace(']', '')\n charge_splits = bracketed_charge_re.split(formula)\n if len(charge_splits) > 1:\n formula = charge_splits[0]\n else:\n formula = formula.split('+')[0].split('-')[0]\n \n stack = [[]]\n last = stack[0]\n tokens = formula_token_matcher_rational.findall(formula)\n # The set of letters in the tokens should match the set of letters\n if check:\n token_letters = set([j for i in tokens for j in i if j in letter_set])\n formula_letters = set(i for i in formula if i in letter_set)\n if formula_letters != token_letters:\n raise Exception('Input may not be a formula; extra letters were detected')\n \n for token in tokens:\n if token == \"(\":\n stack.append([])\n last = stack[-1]\n elif token == \")\":\n temp_dict = {}\n for d in last:\n for ele, count in d.items():\n if ele in temp_dict:\n temp_dict[ele] = temp_dict[ele] + count\n else:\n temp_dict[ele] = count\n stack.pop()\n last = stack[-1]\n last.append(temp_dict)\n elif token.isalpha():\n last.append({token: 1})\n else:\n v = float(token)\n v_int = int(v)\n if v_int == v:\n v = v_int\n last[-1] = {ele: count*v for ele, count in last[-1].items()}\n ans = {}\n for d in last:\n for ele, count in d.items():\n if ele in ans:\n ans[ele] = ans[ele] + count\n else:\n ans[ele] = count\n return ans", "response": "Improved formula parser which handles braces and multipliers and rational element counts."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nestablishes a connection to the chat server. Returns when an error has occurred or a disconnect has been called.", "response": "async def connect(self):\n \"\"\"Establish a connection to the chat server.\n\n Returns when an error has occurred, or :func:`disconnect` has been\n called.\n \"\"\"\n proxy = os.environ.get('HTTP_PROXY')\n self._session = http_utils.Session(self._cookies, proxy=proxy)\n try:\n self._channel = channel.Channel(\n self._session, self._max_retries, self._retry_backoff_base\n )\n\n # Forward the Channel events to the Client events.\n self._channel.on_connect.add_observer(self.on_connect.fire)\n self._channel.on_reconnect.add_observer(self.on_reconnect.fire)\n self._channel.on_disconnect.add_observer(self.on_disconnect.fire)\n self._channel.on_receive_array.add_observer(self._on_receive_array)\n\n # Wrap the coroutine in a Future so it can be cancelled.\n self._listen_future = asyncio.ensure_future(self._channel.listen())\n # Listen for StateUpdate messages from the Channel until it\n # disconnects.\n try:\n await self._listen_future\n except asyncio.CancelledError:\n # If this task is cancelled, we need to cancel our child task\n # as well. We don't need an additional yield because listen\n # cancels immediately.\n self._listen_future.cancel()\n logger.info(\n 'Client.connect returning because Channel.listen returned'\n )\n finally:\n await self._session.close()"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn the request header for use when constructing requests.", "response": "def get_request_header(self):\n \"\"\"Return ``request_header`` for use when constructing requests.\n\n Returns:\n Populated request header.\n \"\"\"\n # resource is allowed to be null if it's not available yet (the Chrome\n # client does this for the first getentitybyid call)\n if self._client_id is not None:\n self._request_header.client_identifier.resource = self._client_id\n return self._request_header"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nsets this client as active.", "response": "async def set_active(self):\n \"\"\"Set this client as active.\n\n While a client is active, no other clients will raise notifications.\n Call this method whenever there is an indication the user is\n interacting with this client. This method may be called very\n frequently, and it will only make a request when necessary.\n \"\"\"\n is_active = (self._active_client_state ==\n hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE)\n timed_out = (time.time() - self._last_active_secs >\n SETACTIVECLIENT_LIMIT_SECS)\n if not is_active or timed_out:\n # Update these immediately so if the function is called again\n # before the API request finishes, we don't start extra requests.\n self._active_client_state = (\n hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE\n )\n self._last_active_secs = time.time()\n\n # The first time this is called, we need to retrieve the user's\n # email address.\n if self._email is None:\n try:\n get_self_info_request = hangouts_pb2.GetSelfInfoRequest(\n request_header=self.get_request_header(),\n )\n get_self_info_response = await self.get_self_info(\n get_self_info_request\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to find email address: {}'\n .format(e))\n return\n self._email = (\n get_self_info_response.self_entity.properties.email[0]\n )\n\n # If the client_id hasn't been received yet, we can't set the\n # active client.\n if self._client_id is None:\n logger.info(\n 'Cannot set active client until client_id is received'\n )\n return\n\n try:\n set_active_request = hangouts_pb2.SetActiveClientRequest(\n request_header=self.get_request_header(),\n is_active=True,\n full_jid=\"{}/{}\".format(self._email, self._client_id),\n timeout_secs=ACTIVE_TIMEOUT_SECS,\n )\n await self.set_active_client(set_active_request)\n except exceptions.NetworkError as e:\n logger.warning('Failed to set active client: {}'.format(e))\n else:\n logger.info('Set active client for {} seconds'\n .format(ACTIVE_TIMEOUT_SECS))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nupload an image to the chat message.", "response": "async def upload_image(self, image_file, filename=None, *,\n return_uploaded_image=False):\n \"\"\"Upload an image that can be later attached to a chat message.\n\n Args:\n image_file: A file-like object containing an image.\n filename (str): (optional) Custom name for the uploaded file.\n return_uploaded_image (bool): (optional) If True, return\n :class:`.UploadedImage` instead of image ID. Defaults to False.\n\n Raises:\n hangups.NetworkError: If the upload request failed.\n\n Returns:\n :class:`.UploadedImage` instance, or ID of the uploaded image.\n \"\"\"\n image_filename = filename or os.path.basename(image_file.name)\n image_data = image_file.read()\n\n # request an upload URL\n res = await self._base_request(\n IMAGE_UPLOAD_URL,\n 'application/x-www-form-urlencoded;charset=UTF-8', 'json',\n json.dumps({\n \"protocolVersion\": \"0.8\",\n \"createSessionRequest\": {\n \"fields\": [{\n \"external\": {\n \"name\": \"file\",\n \"filename\": image_filename,\n \"put\": {},\n \"size\": len(image_data)\n }\n }]\n }\n })\n )\n\n try:\n upload_url = self._get_upload_session_status(res)[\n 'externalFieldTransfers'\n ][0]['putInfo']['url']\n except KeyError:\n raise exceptions.NetworkError(\n 'image upload failed: can not acquire an upload url'\n )\n\n # upload the image data using the upload_url to get the upload info\n res = await self._base_request(\n upload_url, 'application/octet-stream', 'json', image_data\n )\n\n try:\n raw_info = (\n self._get_upload_session_status(res)['additionalInfo']\n ['uploader_service.GoogleRupioAdditionalInfo']\n ['completionInfo']['customerSpecificInfo']\n )\n image_id = raw_info['photoid']\n url = raw_info['url']\n except KeyError:\n raise exceptions.NetworkError(\n 'image upload failed: can not fetch upload info'\n )\n\n result = UploadedImage(image_id=image_id, url=url)\n return result if return_uploaded_image else result.image_id"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _get_upload_session_status(res):\n response = json.loads(res.body.decode())\n if 'sessionStatus' not in response:\n try:\n info = (\n response['errorMessage']['additionalInfo']\n ['uploader_service.GoogleRupioAdditionalInfo']\n ['completionInfo']['customerSpecificInfo']\n )\n reason = '{} : {}'.format(info['status'], info['message'])\n except KeyError:\n reason = 'unknown reason'\n raise exceptions.NetworkError('image upload failed: {}'.format(\n reason\n ))\n return response['sessionStatus']", "response": "Parse the response to obtain status."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\nasync def _on_receive_array(self, array):\n if array[0] == 'noop':\n pass # This is just a keep-alive, ignore it.\n else:\n wrapper = json.loads(array[0]['p'])\n # Wrapper appears to be a Protocol Buffer message, but encoded via\n # field numbers as dictionary keys. Since we don't have a parser\n # for that, parse it ad-hoc here.\n if '3' in wrapper:\n # This is a new client_id.\n self._client_id = wrapper['3']['2']\n logger.info('Received new client_id: %r', self._client_id)\n # Once client_id is received, the channel is ready to have\n # services added.\n await self._add_channel_services()\n if '2' in wrapper:\n pblite_message = json.loads(wrapper['2']['2'])\n if pblite_message[0] == 'cbu':\n # This is a (Client)BatchUpdate containing StateUpdate\n # messages.\n batch_update = hangouts_pb2.BatchUpdate()\n pblite.decode(batch_update, pblite_message,\n ignore_first_item=True)\n for state_update in batch_update.state_update:\n logger.debug('Received StateUpdate:\\n%s', state_update)\n header = state_update.state_update_header\n self._active_client_state = header.active_client_state\n await self.on_state_update.fire(state_update)\n else:\n logger.info('Ignoring message: %r', pblite_message[0])", "response": "Parse the channel array and call the appropriate events."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\nasync def _add_channel_services(self):\n logger.info('Adding channel services...')\n # Based on what Hangouts for Chrome does over 2 requests, this is\n # trimmed down to 1 request that includes the bare minimum to make\n # things work.\n services = [\"babel\", \"babel_presence_last_seen\"]\n map_list = [\n dict(p=json.dumps({\"3\": {\"1\": {\"1\": service}}}))\n for service in services\n ]\n await self._channel.send_maps(map_list)\n logger.info('Channel services added')", "response": "Add services to the channel."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\nasync def _pb_request(self, endpoint, request_pb, response_pb):\n logger.debug('Sending Protocol Buffer request %s:\\n%s', endpoint,\n request_pb)\n res = await self._base_request(\n 'https://clients6.google.com/chat/v1/{}'.format(endpoint),\n 'application/x-protobuf', # Request body is Protocol Buffer.\n 'proto', # Response body is Protocol Buffer.\n request_pb.SerializeToString()\n )\n try:\n response_pb.ParseFromString(base64.b64decode(res.body))\n except binascii.Error as e:\n raise exceptions.NetworkError(\n 'Failed to decode base64 response: {}'.format(e)\n )\n except google.protobuf.message.DecodeError as e:\n raise exceptions.NetworkError(\n 'Failed to decode Protocol Buffer response: {}'.format(e)\n )\n logger.debug('Received Protocol Buffer response:\\n%s', response_pb)\n status = response_pb.response_header.status\n if status != hangouts_pb2.RESPONSE_STATUS_OK:\n description = response_pb.response_header.error_description\n raise exceptions.NetworkError(\n 'Request failed with status {}: \\'{}\\''\n .format(status, description)\n )", "response": "Send a Protocol Buffer formatted chat API request."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\nasync def _base_request(self, url, content_type, response_type, data):\n headers = {\n 'content-type': content_type,\n # This header is required for Protocol Buffer responses. It causes\n # them to be base64 encoded:\n 'X-Goog-Encode-Response-If-Executable': 'base64',\n }\n params = {\n # \"alternative representation type\" (desired response format).\n 'alt': response_type,\n # API key (required to avoid 403 Forbidden \"Daily Limit for\n # Unauthenticated Use Exceeded. Continued use requires signup\").\n 'key': API_KEY,\n }\n res = await self._session.fetch(\n 'post', url, headers=headers, params=params, data=data,\n )\n return res", "response": "Send a generic authenticated POST request."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def add_user(self, add_user_request):\n response = hangouts_pb2.AddUserResponse()\n await self._pb_request('conversations/adduser',\n add_user_request, response)\n return response", "response": "Invite users to join an existing group conversation."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncreates a new conversation.", "response": "async def create_conversation(self, create_conversation_request):\n \"\"\"Create a new conversation.\"\"\"\n response = hangouts_pb2.CreateConversationResponse()\n await self._pb_request('conversations/createconversation',\n create_conversation_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nleave a one - to - one conversation.", "response": "async def delete_conversation(self, delete_conversation_request):\n \"\"\"Leave a one-to-one conversation.\n\n One-to-one conversations are \"sticky\"; they can't actually be deleted.\n This API clears the event history of the specified conversation up to\n ``delete_upper_bound_timestamp``, hiding it if no events remain.\n \"\"\"\n response = hangouts_pb2.DeleteConversationResponse()\n await self._pb_request('conversations/deleteconversation',\n delete_conversation_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\nasync def easter_egg(self, easter_egg_request):\n response = hangouts_pb2.EasterEggResponse()\n await self._pb_request('conversations/easteregg',\n easter_egg_request, response)\n return response", "response": "Send an easter egg event to a conversation."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\nasync def get_conversation(self, get_conversation_request):\n response = hangouts_pb2.GetConversationResponse()\n await self._pb_request('conversations/getconversation',\n get_conversation_request, response)\n return response", "response": "Get conversation info and recent events."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn one or more user entities.", "response": "async def get_entity_by_id(self, get_entity_by_id_request):\n \"\"\"Return one or more user entities.\n\n Searching by phone number only finds entities when their phone number\n is in your contacts (and not always even then), and can't be used to\n find Google Voice contacts.\n \"\"\"\n response = hangouts_pb2.GetEntityByIdResponse()\n await self._pb_request('contacts/getentitybyid',\n get_entity_by_id_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngetting URL to allow others to join a group conversation.", "response": "async def get_group_conversation_url(self,\n get_group_conversation_url_request):\n \"\"\"Get URL to allow others to join a group conversation.\"\"\"\n response = hangouts_pb2.GetGroupConversationUrlResponse()\n await self._pb_request('conversations/getgroupconversationurl',\n get_group_conversation_url_request,\n response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\nasync def get_self_info(self, get_self_info_request):\n response = hangouts_pb2.GetSelfInfoResponse()\n await self._pb_request('contacts/getselfinfo',\n get_self_info_request, response)\n return response", "response": "Returns info about the current user."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning presence status for a list of users.", "response": "async def query_presence(self, query_presence_request):\n \"\"\"Return presence status for a list of users.\"\"\"\n response = hangouts_pb2.QueryPresenceResponse()\n await self._pb_request('presence/querypresence',\n query_presence_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nremoving a participant from a group conversation.", "response": "async def remove_user(self, remove_user_request):\n \"\"\"Remove a participant from a group conversation.\"\"\"\n response = hangouts_pb2.RemoveUserResponse()\n await self._pb_request('conversations/removeuser',\n remove_user_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\nasync def rename_conversation(self, rename_conversation_request):\n response = hangouts_pb2.RenameConversationResponse()\n await self._pb_request('conversations/renameconversation',\n rename_conversation_request, response)\n return response", "response": "Rename a conversation.\n\n Both group and one-to-one conversations may be renamed, but the\n official Hangouts clients have mixed support for one-to-one\n conversations with custom names."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning user entities based on a query.", "response": "async def search_entities(self, search_entities_request):\n \"\"\"Return user entities based on a query.\"\"\"\n response = hangouts_pb2.SearchEntitiesResponse()\n await self._pb_request('contacts/searchentities',\n search_entities_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nsends a chat message to a conversation.", "response": "async def send_chat_message(self, send_chat_message_request):\n \"\"\"Send a chat message to a conversation.\"\"\"\n response = hangouts_pb2.SendChatMessageResponse()\n await self._pb_request('conversations/sendchatmessage',\n send_chat_message_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nenable or disable message history in a conversation.", "response": "async def modify_otr_status(self, modify_otr_status_request):\n \"\"\"Enable or disable message history in a conversation.\"\"\"\n response = hangouts_pb2.ModifyOTRStatusResponse()\n await self._pb_request('conversations/modifyotrstatus',\n modify_otr_status_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\nasync def send_offnetwork_invitation(\n self, send_offnetwork_invitation_request\n ):\n \"\"\"Send an email to invite a non-Google contact to Hangouts.\"\"\"\n response = hangouts_pb2.SendOffnetworkInvitationResponse()\n await self._pb_request('devices/sendoffnetworkinvitation',\n send_offnetwork_invitation_request,\n response)\n return response", "response": "Send an email to invite a non - Google contact to Hangouts."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nset the active client.", "response": "async def set_active_client(self, set_active_client_request):\n \"\"\"Set the active client.\"\"\"\n response = hangouts_pb2.SetActiveClientResponse()\n await self._pb_request('clients/setactiveclient',\n set_active_client_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\nasync def set_conversation_notification_level(\n self, set_conversation_notification_level_request\n ):\n \"\"\"Set the notification level of a conversation.\"\"\"\n response = hangouts_pb2.SetConversationNotificationLevelResponse()\n await self._pb_request(\n 'conversations/setconversationnotificationlevel',\n set_conversation_notification_level_request, response\n )\n return response", "response": "Set the notification level of a conversation."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nsetting focus to a conversation.", "response": "async def set_focus(self, set_focus_request):\n \"\"\"Set focus to a conversation.\"\"\"\n response = hangouts_pb2.SetFocusResponse()\n await self._pb_request('conversations/setfocus',\n set_focus_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\nasync def set_group_link_sharing_enabled(\n self, set_group_link_sharing_enabled_request\n ):\n \"\"\"Set whether group link sharing is enabled for a conversation.\"\"\"\n response = hangouts_pb2.SetGroupLinkSharingEnabledResponse()\n await self._pb_request('conversations/setgrouplinksharingenabled',\n set_group_link_sharing_enabled_request,\n response)\n return response", "response": "Sets whether group link sharing is enabled for a conversation."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\nasync def set_presence(self, set_presence_request):\n response = hangouts_pb2.SetPresenceResponse()\n await self._pb_request('presence/setpresence',\n set_presence_request, response)\n return response", "response": "Set the presence status."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\nasync def set_typing(self, set_typing_request):\n response = hangouts_pb2.SetTypingResponse()\n await self._pb_request('conversations/settyping',\n set_typing_request, response)\n return response", "response": "Sets the typing status of a conversation."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nlists all events occurring at or after a timestamp.", "response": "async def sync_all_new_events(self, sync_all_new_events_request):\n \"\"\"List all events occurring at or after a timestamp.\"\"\"\n response = hangouts_pb2.SyncAllNewEventsResponse()\n await self._pb_request('conversations/syncallnewevents',\n sync_all_new_events_request, response)\n return response"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\nasync def sync_recent_conversations(\n self, sync_recent_conversations_request\n ):\n \"\"\"Return info on recent conversations and their events.\"\"\"\n response = hangouts_pb2.SyncRecentConversationsResponse()\n await self._pb_request('conversations/syncrecentconversations',\n sync_recent_conversations_request,\n response)\n return response", "response": "Return info on recent conversations and their events."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\nasync def update_watermark(self, update_watermark_request):\n response = hangouts_pb2.UpdateWatermarkResponse()\n await self._pb_request('conversations/updatewatermark',\n update_watermark_request, response)\n return response", "response": "Update the watermark ( read timestamp of a conversation."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef from_timestamp(microsecond_timestamp):\n # Create datetime without losing precision from floating point (yes, this\n # is actually needed):\n return datetime.datetime.fromtimestamp(\n microsecond_timestamp // 1000000, datetime.timezone.utc\n ).replace(microsecond=(microsecond_timestamp % 1000000))", "response": "Convert a microsecond timestamp to a UTC datetime instance."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nconverting hangouts_pb2. ParticipantId to UserID.", "response": "def from_participantid(participant_id):\n \"\"\"Convert hangouts_pb2.ParticipantId to UserID.\"\"\"\n return user.UserID(\n chat_id=participant_id.chat_id,\n gaia_id=participant_id.gaia_id\n )"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef to_participantid(user_id):\n return hangouts_pb2.ParticipantId(\n chat_id=user_id.chat_id,\n gaia_id=user_id.gaia_id\n )", "response": "Convert a userID to a ParticipantId."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef parse_typing_status_message(p):\n return TypingStatusMessage(\n conv_id=p.conversation_id.id,\n user_id=from_participantid(p.sender_id),\n timestamp=from_timestamp(p.timestamp),\n status=p.type,\n )", "response": "Return TypingStatusMessage from hangouts_pb2. SetTypingNotification."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef parse_watermark_notification(p):\n return WatermarkNotification(\n conv_id=p.conversation_id.id,\n user_id=from_participantid(p.sender_id),\n read_timestamp=from_timestamp(\n p.latest_read_timestamp\n ),\n )", "response": "Return WatermarkNotification from hangouts_pb2. WatermarkNotification."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the authorization headers for API request.", "response": "def _get_authorization_headers(sapisid_cookie):\n \"\"\"Return authorization headers for API request.\"\"\"\n # It doesn't seem to matter what the url and time are as long as they are\n # consistent.\n time_msec = int(time.time() * 1000)\n auth_string = '{} {} {}'.format(time_msec, sapisid_cookie, ORIGIN_URL)\n auth_hash = hashlib.sha1(auth_string.encode()).hexdigest()\n sapisidhash = 'SAPISIDHASH {}_{}'.format(time_msec, auth_hash)\n return {\n 'authorization': sapisidhash,\n 'x-origin': ORIGIN_URL,\n 'x-goog-authuser': '0',\n }"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def fetch(self, method, url, params=None, headers=None, data=None):\n logger.debug('Sending request %s %s:\\n%r', method, url, data)\n for retry_num in range(MAX_RETRIES):\n try:\n async with self.fetch_raw(method, url, params=params,\n headers=headers, data=data) as res:\n async with async_timeout.timeout(REQUEST_TIMEOUT):\n body = await res.read()\n logger.debug('Received response %d %s:\\n%r',\n res.status, res.reason, body)\n except asyncio.TimeoutError:\n error_msg = 'Request timed out'\n except aiohttp.ServerDisconnectedError as err:\n error_msg = 'Server disconnected error: {}'.format(err)\n except (aiohttp.ClientError, ValueError) as err:\n error_msg = 'Request connection error: {}'.format(err)\n else:\n break\n logger.info('Request attempt %d failed: %s', retry_num, error_msg)\n else:\n logger.info('Request failed after %d attempts', MAX_RETRIES)\n raise exceptions.NetworkError(error_msg)\n\n if res.status != 200:\n logger.info('Request returned unexpected status: %d %s',\n res.status, res.reason)\n raise exceptions.NetworkError(\n 'Request return unexpected status: {}: {}'\n .format(res.status, res.reason)\n )\n\n return FetchResponse(res.status, body)", "response": "Make an HTTP request to the specified URL and return the response."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nmake an HTTP request using aiohttp directly.", "response": "def fetch_raw(self, method, url, params=None, headers=None, data=None):\n \"\"\"Make an HTTP request using aiohttp directly.\n\n Automatically uses configured HTTP proxy, and adds Google authorization\n header and cookies.\n\n Args:\n method (str): Request method.\n url (str): Request URL.\n params (dict): (optional) Request query string parameters.\n headers (dict): (optional) Request headers.\n data: (str): (optional) Request body data.\n\n Returns:\n aiohttp._RequestContextManager: ContextManager for a HTTP response.\n\n Raises:\n See ``aiohttp.ClientSession.request``.\n \"\"\"\n # Ensure we don't accidentally send the authorization header to a\n # non-Google domain:\n if not urllib.parse.urlparse(url).hostname.endswith('.google.com'):\n raise Exception('expected google.com domain')\n\n headers = headers or {}\n headers.update(self._authorization_headers)\n return self._session.request(\n method, url, params=params, headers=headers, data=data,\n proxy=self._proxy\n )"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nsearching for entities by phone number email or gaia_id.", "response": "async def lookup_entities(client, args):\n \"\"\"Search for entities by phone number, email, or gaia_id.\"\"\"\n lookup_spec = _get_lookup_spec(args.entity_identifier)\n request = hangups.hangouts_pb2.GetEntityByIdRequest(\n request_header=client.get_request_header(),\n batch_lookup_spec=[lookup_spec],\n )\n res = await client.get_entity_by_id(request)\n\n # Print the list of entities in the response.\n for entity_result in res.entity_result:\n for entity in entity_result.entity:\n print(entity)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _get_lookup_spec(identifier):\n if identifier.startswith('+'):\n return hangups.hangouts_pb2.EntityLookupSpec(\n phone=identifier, create_offnetwork_gaia=True\n )\n elif '@' in identifier:\n return hangups.hangouts_pb2.EntityLookupSpec(\n email=identifier, create_offnetwork_gaia=True\n )\n else:\n return hangups.hangouts_pb2.EntityLookupSpec(gaia_id=identifier)", "response": "Return EntityLookupSpec from phone number email address or gaia ID."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns a readable name for a conversation.", "response": "def get_conv_name(conv, truncate=False, show_unread=False):\n \"\"\"Return a readable name for a conversation.\n\n If the conversation has a custom name, use the custom name. Otherwise, for\n one-to-one conversations, the name is the full name of the other user. For\n group conversations, the name is a comma-separated list of first names. If\n the group conversation is empty, the name is \"Empty Conversation\".\n\n If truncate is true, only show up to two names in a group conversation.\n\n If show_unread is True, if there are unread chat messages, show the number\n of unread chat messages in parentheses after the conversation name.\n \"\"\"\n num_unread = len([conv_event for conv_event in conv.unread_events if\n isinstance(conv_event, hangups.ChatMessageEvent) and\n not conv.get_user(conv_event.user_id).is_self])\n if show_unread and num_unread > 0:\n postfix = ' ({})'.format(num_unread)\n else:\n postfix = ''\n if conv.name is not None:\n return conv.name + postfix\n else:\n participants = sorted(\n (user for user in conv.users if not user.is_self),\n key=lambda user: user.id_\n )\n names = [user.first_name for user in participants]\n if not participants:\n return \"Empty Conversation\" + postfix\n if len(participants) == 1:\n return participants[0].full_name + postfix\n elif truncate and len(participants) > 2:\n return (', '.join(names[:2] + ['+{}'.format(len(names) - 2)]) +\n postfix)\n else:\n return ', '.join(names) + postfix"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef add_color_to_scheme(scheme, name, foreground, background, palette_colors):\n if foreground is None and background is None:\n return scheme\n\n new_scheme = []\n for item in scheme:\n if item[0] == name:\n if foreground is None:\n foreground = item[1]\n if background is None:\n background = item[2]\n if palette_colors > 16:\n new_scheme.append((name, '', '', '', foreground, background))\n else:\n new_scheme.append((name, foreground, background))\n else:\n new_scheme.append(item)\n return new_scheme", "response": "Add foreground and background colours to a color scheme"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\nasync def build_user_conversation_list(client):\n conv_states, sync_timestamp = await _sync_all_conversations(client)\n\n # Retrieve entities participating in all conversations.\n required_user_ids = set()\n for conv_state in conv_states:\n required_user_ids |= {\n user.UserID(chat_id=part.id.chat_id, gaia_id=part.id.gaia_id)\n for part in conv_state.conversation.participant_data\n }\n required_entities = []\n if required_user_ids:\n logger.debug('Need to request additional users: {}'\n .format(required_user_ids))\n try:\n response = await client.get_entity_by_id(\n hangouts_pb2.GetEntityByIdRequest(\n request_header=client.get_request_header(),\n batch_lookup_spec=[\n hangouts_pb2.EntityLookupSpec(\n gaia_id=user_id.gaia_id,\n create_offnetwork_gaia=True,\n )\n for user_id in required_user_ids\n ],\n )\n )\n for entity_result in response.entity_result:\n required_entities.extend(entity_result.entity)\n except exceptions.NetworkError as e:\n logger.warning('Failed to request missing users: {}'.format(e))\n\n # Build list of conversation participants.\n conv_part_list = []\n for conv_state in conv_states:\n conv_part_list.extend(conv_state.conversation.participant_data)\n\n # Retrieve self entity.\n get_self_info_response = await client.get_self_info(\n hangouts_pb2.GetSelfInfoRequest(\n request_header=client.get_request_header(),\n )\n )\n self_entity = get_self_info_response.self_entity\n\n user_list = user.UserList(client, self_entity, required_entities,\n conv_part_list)\n conversation_list = ConversationList(client, conv_states,\n user_list, sync_timestamp)\n return (user_list, conversation_list)", "response": "Builds a list of conversations and participants for a user."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nlists of users in the conversation.", "response": "def users(self):\n \"\"\"List of conversation participants (:class:`~hangups.user.User`).\"\"\"\n return [self._user_list.get_user(user.UserID(chat_id=part.id.chat_id,\n gaia_id=part.id.gaia_id))\n for part in self._conversation.participant_data]"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef unread_events(self):\n return [conv_event for conv_event in self._events\n if conv_event.timestamp > self.latest_read_timestamp]", "response": "Returns a list of all unread event items in the event cache sorted oldest to newest."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ntrue if the notification level for this conversation is quiet.", "response": "def is_quiet(self):\n \"\"\"``True`` if notification level for this conversation is quiet.\"\"\"\n level = self._conversation.self_conversation_state.notification_level\n return level == hangouts_pb2.NOTIFICATION_LEVEL_QUIET"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nhandles a watermark notification.", "response": "def _on_watermark_notification(self, notif):\n \"\"\"Handle a watermark notification.\"\"\"\n # Update the conversation:\n if self.get_user(notif.user_id).is_self:\n logger.info('latest_read_timestamp for {} updated to {}'\n .format(self.id_, notif.read_timestamp))\n self_conversation_state = (\n self._conversation.self_conversation_state\n )\n self_conversation_state.self_read_state.latest_read_timestamp = (\n parsers.to_timestamp(notif.read_timestamp)\n )\n # Update the participants' watermarks:\n previous_timestamp = self._watermarks.get(\n notif.user_id,\n datetime.datetime.min.replace(tzinfo=datetime.timezone.utc)\n )\n if notif.read_timestamp > previous_timestamp:\n logger.info(('latest_read_timestamp for conv {} participant {}' +\n ' updated to {}').format(self.id_,\n notif.user_id.chat_id,\n notif.read_timestamp))\n self._watermarks[notif.user_id] = notif.read_timestamp"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef update_conversation(self, conversation):\n # StateUpdate.conversation is actually a delta; fields that aren't\n # specified are assumed to be unchanged. Until this class is\n # refactored, hide this by saving and restoring previous values where\n # necessary.\n\n new_state = conversation.self_conversation_state\n old_state = self._conversation.self_conversation_state\n self._conversation = conversation\n\n # delivery_medium_option\n if not new_state.delivery_medium_option:\n new_state.delivery_medium_option.extend(\n old_state.delivery_medium_option\n )\n\n # latest_read_timestamp\n old_timestamp = old_state.self_read_state.latest_read_timestamp\n new_timestamp = new_state.self_read_state.latest_read_timestamp\n if new_timestamp == 0:\n new_state.self_read_state.latest_read_timestamp = old_timestamp\n\n # user_read_state(s)\n for new_entry in conversation.read_state:\n tstamp = parsers.from_timestamp(new_entry.latest_read_timestamp)\n if tstamp == 0:\n continue\n uid = parsers.from_participantid(new_entry.participant_id)\n if uid not in self._watermarks or self._watermarks[uid] < tstamp:\n self._watermarks[uid] = tstamp", "response": "Updates the internal state of the conversation."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _wrap_event(event_):\n cls = conversation_event.ConversationEvent\n if event_.HasField('chat_message'):\n cls = conversation_event.ChatMessageEvent\n elif event_.HasField('otr_modification'):\n cls = conversation_event.OTREvent\n elif event_.HasField('conversation_rename'):\n cls = conversation_event.RenameEvent\n elif event_.HasField('membership_change'):\n cls = conversation_event.MembershipChangeEvent\n elif event_.HasField('hangout_event'):\n cls = conversation_event.HangoutEvent\n elif event_.HasField('group_link_sharing_modification'):\n cls = conversation_event.GroupLinkSharingModificationEvent\n return cls(event_)", "response": "Wrap hangouts_pb2. Event in ConversationEvent subclass."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nadd an event to the conversation.", "response": "def add_event(self, event_):\n \"\"\"Add an event to the conversation.\n\n This method is used by :class:`.ConversationList` to maintain this\n instance.\n\n Args:\n event_: ``Event`` message.\n\n Returns:\n :class:`.ConversationEvent` representing the event.\n \"\"\"\n conv_event = self._wrap_event(event_)\n if conv_event.id_ not in self._events_dict:\n self._events.append(conv_event)\n self._events_dict[conv_event.id_] = conv_event\n else:\n # If this happens, there's probably a bug.\n logger.info('Conversation %s ignoring duplicate event %s',\n self.id_, conv_event.id_)\n return None\n return conv_event"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns default delivery medium to use for sending messages.", "response": "def _get_default_delivery_medium(self):\n \"\"\"Return default DeliveryMedium to use for sending messages.\n\n Use the first option, or an option that's marked as the current\n default.\n \"\"\"\n medium_options = (\n self._conversation.self_conversation_state.delivery_medium_option\n )\n try:\n default_medium = medium_options[0].delivery_medium\n except IndexError:\n logger.warning('Conversation %r has no delivery medium', self.id_)\n default_medium = hangouts_pb2.DeliveryMedium(\n medium_type=hangouts_pb2.DELIVERY_MEDIUM_BABEL\n )\n for medium_option in medium_options:\n if medium_option.current_default:\n default_medium = medium_option.delivery_medium\n return default_medium"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn EventRequestHeader for conversation.", "response": "def _get_event_request_header(self):\n \"\"\"Return EventRequestHeader for conversation.\"\"\"\n otr_status = (hangouts_pb2.OFF_THE_RECORD_STATUS_OFF_THE_RECORD\n if self.is_off_the_record else\n hangouts_pb2.OFF_THE_RECORD_STATUS_ON_THE_RECORD)\n return hangouts_pb2.EventRequestHeader(\n conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n client_generated_id=self._client.get_client_generated_id(),\n expected_otr=otr_status,\n delivery_medium=self._get_default_delivery_medium(),\n )"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\nasync def send_message(self, segments, image_file=None, image_id=None,\n image_user_id=None):\n \"\"\"Send a message to this conversation.\n\n A per-conversation lock is acquired to ensure that messages are sent in\n the correct order when this method is called multiple times\n asynchronously.\n\n Args:\n segments: List of :class:`.ChatMessageSegment` objects to include\n in the message.\n image_file: (optional) File-like object containing an image to be\n attached to the message.\n image_id: (optional) ID of an Picasa photo to be attached to the\n message. If you specify both ``image_file`` and ``image_id``\n together, ``image_file`` takes precedence and ``image_id`` will\n be ignored.\n image_user_id: (optional) Picasa user ID, required only if\n ``image_id`` refers to an image from a different Picasa user,\n such as Google's sticker user.\n\n Raises:\n .NetworkError: If the message cannot be sent.\n \"\"\"\n async with self._send_message_lock:\n if image_file:\n try:\n uploaded_image = await self._client.upload_image(\n image_file, return_uploaded_image=True\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to upload image: {}'.format(e))\n raise\n image_id = uploaded_image.image_id\n try:\n request = hangouts_pb2.SendChatMessageRequest(\n request_header=self._client.get_request_header(),\n event_request_header=self._get_event_request_header(),\n message_content=hangouts_pb2.MessageContent(\n segment=[seg.serialize() for seg in segments],\n ),\n )\n if image_id is not None:\n request.existing_media.photo.photo_id = image_id\n if image_user_id is not None:\n request.existing_media.photo.user_id = image_user_id\n request.existing_media.photo.is_custom_user_id = True\n await self._client.send_chat_message(request)\n except exceptions.NetworkError as e:\n logger.warning('Failed to send message: {}'.format(e))\n raise", "response": "Sends a message to the current conversation."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def leave(self):\n is_group_conversation = (self._conversation.type ==\n hangouts_pb2.CONVERSATION_TYPE_GROUP)\n try:\n if is_group_conversation:\n await self._client.remove_user(\n hangouts_pb2.RemoveUserRequest(\n request_header=self._client.get_request_header(),\n event_request_header=self._get_event_request_header(),\n )\n )\n else:\n await self._client.delete_conversation(\n hangouts_pb2.DeleteConversationRequest(\n request_header=self._client.get_request_header(),\n conversation_id=hangouts_pb2.ConversationId(\n id=self.id_\n ),\n delete_upper_bound_timestamp=parsers.to_timestamp(\n datetime.datetime.now(tz=datetime.timezone.utc)\n )\n )\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to leave conversation: {}'.format(e))\n raise", "response": "Leaves the current conversation."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nrename this conversation. Hangouts only officially supports renaming group conversations, so custom names for one-to-one conversations may or may not appear in all first party clients. Args: name (str): New name. Raises: .NetworkError: If conversation cannot be renamed.", "response": "async def rename(self, name):\n \"\"\"Rename this conversation.\n\n Hangouts only officially supports renaming group conversations, so\n custom names for one-to-one conversations may or may not appear in all\n first party clients.\n\n Args:\n name (str): New name.\n\n Raises:\n .NetworkError: If conversation cannot be renamed.\n \"\"\"\n await self._client.rename_conversation(\n hangouts_pb2.RenameConversationRequest(\n request_header=self._client.get_request_header(),\n new_name=name,\n event_request_header=self._get_event_request_header(),\n )\n )"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nset the notification level of this conversation.", "response": "async def set_notification_level(self, level):\n \"\"\"Set the notification level of this conversation.\n\n Args:\n level: ``NOTIFICATION_LEVEL_QUIET`` to disable notifications, or\n ``NOTIFICATION_LEVEL_RING`` to enable them.\n\n Raises:\n .NetworkError: If the request fails.\n \"\"\"\n await self._client.set_conversation_notification_level(\n hangouts_pb2.SetConversationNotificationLevelRequest(\n request_header=self._client.get_request_header(),\n conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n level=level,\n )\n )"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\nasync def set_typing(self, typing=hangouts_pb2.TYPING_TYPE_STARTED):\n # TODO: Add rate-limiting to avoid unnecessary requests.\n try:\n await self._client.set_typing(\n hangouts_pb2.SetTypingRequest(\n request_header=self._client.get_request_header(),\n conversation_id=hangouts_pb2.ConversationId(id=self.id_),\n type=typing,\n )\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to set typing status: {}'.format(e))\n raise", "response": "Sets the typing status in this conversation."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nupdating the timestamp of the latest event which has been read.", "response": "async def update_read_timestamp(self, read_timestamp=None):\n \"\"\"Update the timestamp of the latest event which has been read.\n\n This method will avoid making an API request if it will have no effect.\n\n Args:\n read_timestamp (datetime.datetime): (optional) Timestamp to set.\n Defaults to the timestamp of the newest event.\n\n Raises:\n .NetworkError: If the timestamp cannot be updated.\n \"\"\"\n if read_timestamp is None:\n read_timestamp = (self.events[-1].timestamp if self.events else\n datetime.datetime.now(datetime.timezone.utc))\n if read_timestamp > self.latest_read_timestamp:\n logger.info(\n 'Setting {} latest_read_timestamp from {} to {}'\n .format(self.id_, self.latest_read_timestamp, read_timestamp)\n )\n # Prevent duplicate requests by updating the conversation now.\n state = self._conversation.self_conversation_state\n state.self_read_state.latest_read_timestamp = (\n parsers.to_timestamp(read_timestamp)\n )\n try:\n await self._client.update_watermark(\n hangouts_pb2.UpdateWatermarkRequest(\n request_header=self._client.get_request_header(),\n conversation_id=hangouts_pb2.ConversationId(\n id=self.id_\n ),\n last_read_timestamp=parsers.to_timestamp(\n read_timestamp\n ),\n )\n )\n except exceptions.NetworkError as e:\n logger.warning('Failed to update read timestamp: {}'.format(e))\n raise"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngets events from this conversation.", "response": "async def get_events(self, event_id=None, max_events=50):\n \"\"\"Get events from this conversation.\n\n Makes a request to load historical events if necessary.\n\n Args:\n event_id (str): (optional) If provided, return events preceding\n this event, otherwise return the newest events.\n max_events (int): Maximum number of events to return. Defaults to\n 50.\n\n Returns:\n List of :class:`.ConversationEvent` instances, ordered\n newest-first.\n\n Raises:\n KeyError: If ``event_id`` does not correspond to a known event.\n .NetworkError: If the events could not be requested.\n \"\"\"\n if event_id is None:\n # If no event_id is provided, return the newest events in this\n # conversation.\n conv_events = self._events[-1 * max_events:]\n else:\n # If event_id is provided, return the events we have that are\n # older, or request older events if event_id corresponds to the\n # oldest event we have.\n conv_event = self.get_event(event_id)\n if self._events[0].id_ != event_id:\n conv_events = self._events[self._events.index(conv_event) + 1:]\n else:\n logger.info('Loading events for conversation {} before {}'\n .format(self.id_, conv_event.timestamp))\n res = await self._client.get_conversation(\n hangouts_pb2.GetConversationRequest(\n request_header=self._client.get_request_header(),\n conversation_spec=hangouts_pb2.ConversationSpec(\n conversation_id=hangouts_pb2.ConversationId(\n id=self.id_\n )\n ),\n include_event=True,\n max_events_per_conversation=max_events,\n event_continuation_token=self._event_cont_token\n )\n )\n # Certain fields of conversation_state are not populated by\n # SyncRecentConversations. This is the case with the\n # user_read_state fields which are all set to 0 but for the\n # 'self' user. Update here so these fields get populated on the\n # first call to GetConversation.\n if res.conversation_state.HasField('conversation'):\n self.update_conversation(\n res.conversation_state.conversation\n )\n self._event_cont_token = (\n res.conversation_state.event_continuation_token\n )\n conv_events = [self._wrap_event(event) for event\n in res.conversation_state.event]\n logger.info('Loaded {} events for conversation {}'\n .format(len(conv_events), self.id_))\n # Iterate though the events newest to oldest.\n for conv_event in reversed(conv_events):\n # Add event as the new oldest event, unless we already have\n # it.\n if conv_event.id_ not in self._events_dict:\n self._events.insert(0, conv_event)\n self._events_dict[conv_event.id_] = conv_event\n else:\n # If this happens, there's probably a bug.\n logger.info(\n 'Conversation %s ignoring duplicate event %s',\n self.id_, conv_event.id_\n )\n return conv_events"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns the next event in this conversation.", "response": "def next_event(self, event_id, prev=False):\n \"\"\"Get the event following another event in this conversation.\n\n Args:\n event_id (str): ID of the event.\n prev (bool): If ``True``, return the previous event rather than the\n next event. Defaults to ``False``.\n\n Raises:\n KeyError: If no such :class:`.ConversationEvent` is known.\n\n Returns:\n :class:`.ConversationEvent` or ``None`` if there is no following\n event.\n \"\"\"\n i = self.events.index(self._events_dict[event_id])\n if prev and i > 0:\n return self.events[i - 1]\n elif not prev and i + 1 < len(self.events):\n return self.events[i + 1]\n else:\n return None"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_all(self, include_archived=False):\n return [conv for conv in self._conv_dict.values()\n if not conv.is_archived or include_archived]", "response": "Get all the conversations."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nleave a conversation. Args: conv_id (str): ID of conversation to leave.", "response": "async def leave_conversation(self, conv_id):\n \"\"\"Leave a conversation.\n\n Args:\n conv_id (str): ID of conversation to leave.\n \"\"\"\n logger.info('Leaving conversation: {}'.format(conv_id))\n await self._conv_dict[conv_id].leave()\n del self._conv_dict[conv_id]"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nadds a new conversation from a hangouts_pb2. Conversation", "response": "def _add_conversation(self, conversation, events=[],\n event_cont_token=None):\n \"\"\"Add new conversation from hangouts_pb2.Conversation\"\"\"\n # pylint: disable=dangerous-default-value\n conv_id = conversation.conversation_id.id\n logger.debug('Adding new conversation: {}'.format(conv_id))\n conv = Conversation(self._client, self._user_list, conversation,\n events, event_cont_token)\n self._conv_dict[conv_id] = conv\n return conv"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nhandle a state update and fan out to Conversations.", "response": "async def _on_state_update(self, state_update):\n \"\"\"Receive a StateUpdate and fan out to Conversations.\n\n Args:\n state_update: hangouts_pb2.StateUpdate instance\n \"\"\"\n # The state update will include some type of notification:\n notification_type = state_update.WhichOneof('state_update')\n\n # If conversation fields have been updated, the state update will have\n # a conversation containing changed fields. Handle updating the\n # conversation from this delta:\n if state_update.HasField('conversation'):\n try:\n await self._handle_conversation_delta(\n state_update.conversation\n )\n except exceptions.NetworkError:\n logger.warning(\n 'Discarding %s for %s: Failed to fetch conversation',\n notification_type.replace('_', ' '),\n state_update.conversation.conversation_id.id\n )\n return\n\n if notification_type == 'typing_notification':\n await self._handle_set_typing_notification(\n state_update.typing_notification\n )\n elif notification_type == 'watermark_notification':\n await self._handle_watermark_notification(\n state_update.watermark_notification\n )\n elif notification_type == 'event_notification':\n await self._on_event(\n state_update.event_notification.event\n )"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ngets a cached conversation or fetch a missing one.", "response": "async def _get_or_fetch_conversation(self, conv_id):\n \"\"\"Get a cached conversation or fetch a missing conversation.\n\n Args:\n conv_id: string, conversation identifier\n\n Raises:\n NetworkError: If the request to fetch the conversation fails.\n\n Returns:\n :class:`.Conversation` with matching ID.\n \"\"\"\n conv = self._conv_dict.get(conv_id, None)\n if conv is None:\n logger.info('Fetching unknown conversation %s', conv_id)\n res = await self._client.get_conversation(\n hangouts_pb2.GetConversationRequest(\n request_header=self._client.get_request_header(),\n conversation_spec=hangouts_pb2.ConversationSpec(\n conversation_id=hangouts_pb2.ConversationId(\n id=conv_id\n )\n ), include_event=False\n )\n )\n conv_state = res.conversation_state\n event_cont_token = None\n if conv_state.HasField('event_continuation_token'):\n event_cont_token = conv_state.event_continuation_token\n return self._add_conversation(conv_state.conversation,\n event_cont_token=event_cont_token)\n else:\n return conv"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreceive an event and fan out to Conversations.", "response": "async def _on_event(self, event_):\n \"\"\"Receive a hangouts_pb2.Event and fan out to Conversations.\n\n Args:\n event_: hangouts_pb2.Event instance\n \"\"\"\n conv_id = event_.conversation_id.id\n try:\n conv = await self._get_or_fetch_conversation(conv_id)\n except exceptions.NetworkError:\n logger.warning(\n 'Failed to fetch conversation for event notification: %s',\n conv_id\n )\n else:\n self._sync_timestamp = parsers.from_timestamp(event_.timestamp)\n conv_event = conv.add_event(event_)\n # conv_event may be None if the event was a duplicate.\n if conv_event is not None:\n await self.on_event.fire(conv_event)\n await conv.on_event.fire(conv_event)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def _handle_conversation_delta(self, conversation):\n conv_id = conversation.conversation_id.id\n conv = self._conv_dict.get(conv_id, None)\n if conv is None:\n # Ignore the delta and fetch the complete conversation.\n await self._get_or_fetch_conversation(conv_id)\n else:\n # Update conversation using the delta.\n conv.update_conversation(conversation)", "response": "Receive a conversation delta and create or update the conversation."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nhandles a SetTypingNotification message and updates the conversation.", "response": "async def _handle_set_typing_notification(self, set_typing_notification):\n \"\"\"Receive SetTypingNotification and update the conversation.\n\n Args:\n set_typing_notification: hangouts_pb2.SetTypingNotification\n instance\n \"\"\"\n conv_id = set_typing_notification.conversation_id.id\n res = parsers.parse_typing_status_message(set_typing_notification)\n await self.on_typing.fire(res)\n try:\n conv = await self._get_or_fetch_conversation(conv_id)\n except exceptions.NetworkError:\n logger.warning(\n 'Failed to fetch conversation for typing notification: %s',\n conv_id\n )\n else:\n await conv.on_typing.fire(res)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\nasync def _handle_watermark_notification(self, watermark_notification):\n conv_id = watermark_notification.conversation_id.id\n res = parsers.parse_watermark_notification(watermark_notification)\n await self.on_watermark_notification.fire(res)\n try:\n conv = await self._get_or_fetch_conversation(conv_id)\n except exceptions.NetworkError:\n logger.warning(\n 'Failed to fetch conversation for watermark notification: %s',\n conv_id\n )\n else:\n await conv.on_watermark_notification.fire(res)", "response": "Handle a watermark notification and update the conversation."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nupgrade name type of this user.", "response": "def upgrade_name(self, user_):\n \"\"\"Upgrade name type of this user.\n\n Google Voice participants often first appear with no name at all, and\n then get upgraded unpredictably to numbers (\"+12125551212\") or names.\n\n Args:\n user_ (~hangups.user.User): User to upgrade with.\n \"\"\"\n if user_.name_type > self.name_type:\n self.full_name = user_.full_name\n self.first_name = user_.first_name\n self.name_type = user_.name_type\n logger.debug('Added %s name to User \"%s\": %s',\n self.name_type.name.lower(), self.full_name, self)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef from_entity(entity, self_user_id):\n user_id = UserID(chat_id=entity.id.chat_id,\n gaia_id=entity.id.gaia_id)\n return User(user_id, entity.properties.display_name,\n entity.properties.first_name,\n entity.properties.photo_url,\n entity.properties.email,\n (self_user_id == user_id) or (self_user_id is None))", "response": "Construct a User object from an Entity message."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nconstruct a new User object from a ConversationParticipantData message.", "response": "def from_conv_part_data(conv_part_data, self_user_id):\n \"\"\"Construct user from ``ConversationParticipantData`` message.\n\n Args:\n conv_part_id: ``ConversationParticipantData`` message.\n self_user_id (~hangups.user.UserID or None): The ID of the current\n user. If ``None``, assume ``conv_part_id`` is the current user.\n\n Returns:\n :class:`~hangups.user.User` object.\n \"\"\"\n user_id = UserID(chat_id=conv_part_data.id.chat_id,\n gaia_id=conv_part_data.id.gaia_id)\n return User(user_id, conv_part_data.fallback_name, None, None, [],\n (self_user_id == user_id) or (self_user_id is None))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting a user by its ID.", "response": "def get_user(self, user_id):\n \"\"\"Get a user by its ID.\n\n Args:\n user_id (~hangups.user.UserID): The ID of the user.\n\n Raises:\n KeyError: If no such user is known.\n\n Returns:\n :class:`~hangups.user.User` with the given ID.\n \"\"\"\n try:\n return self._user_dict[user_id]\n except KeyError:\n logger.warning('UserList returning unknown User for UserID %s',\n user_id)\n return User(user_id, None, None, None, [], False)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nadd or upgrade User from ConversationParticipantData.", "response": "def _add_user_from_conv_part(self, conv_part):\n \"\"\"Add or upgrade User from ConversationParticipantData.\"\"\"\n user_ = User.from_conv_part_data(conv_part, self._self_user.id_)\n\n existing = self._user_dict.get(user_.id_)\n if existing is None:\n logger.warning('Adding fallback User with %s name \"%s\"',\n user_.name_type.name.lower(), user_.full_name)\n self._user_dict[user_.id_] = user_\n return user_\n else:\n existing.upgrade_name(user_)\n return existing"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef add_observer(self, callback):\n if callback in self._observers:\n raise ValueError('{} is already an observer of {}'\n .format(callback, self))\n self._observers.append(callback)", "response": "Add an observer to this event."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nremoving an observer from this event.", "response": "def remove_observer(self, callback):\n \"\"\"Remove an observer from this event.\n\n Args:\n callback: A function or coroutine callback to remove from this\n event.\n\n Raises:\n ValueError: If the callback is not an observer of this event.\n \"\"\"\n if callback not in self._observers:\n raise ValueError('{} is not an observer of {}'\n .format(callback, self))\n self._observers.remove(callback)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nfire this event calling all observers with the same arguments.", "response": "async def fire(self, *args, **kwargs):\n \"\"\"Fire this event, calling all observers with the same arguments.\"\"\"\n logger.debug('Fired {}'.format(self))\n for observer in self._observers:\n gen = observer(*args, **kwargs)\n if asyncio.iscoroutinefunction(observer):\n await gen"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef markdown(tag):\n return (MARKDOWN_START.format(tag=tag), MARKDOWN_END.format(tag=tag))", "response": "Return start and end regex pattern sequences for simple Markdown tag."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef html(tag):\n return (HTML_START.format(tag=tag), HTML_END.format(tag=tag))", "response": "Return sequence of start and end regex patterns for simple HTML tag"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nruns an example coroutine.", "response": "def run_example(example_coroutine, *extra_args):\n \"\"\"Run a hangups example coroutine.\n\n Args:\n example_coroutine (coroutine): Coroutine to run with a connected\n hangups client and arguments namespace as arguments.\n extra_args (str): Any extra command line arguments required by the\n example.\n \"\"\"\n args = _get_parser(extra_args).parse_args()\n logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING)\n # Obtain hangups authentication cookies, prompting for credentials from\n # standard input if necessary.\n cookies = hangups.auth.get_auth_stdin(args.token_path)\n client = hangups.Client(cookies)\n loop = asyncio.get_event_loop()\n task = asyncio.ensure_future(_async_main(example_coroutine, client, args),\n loop=loop)\n\n try:\n loop.run_until_complete(task)\n except KeyboardInterrupt:\n task.cancel()\n loop.run_until_complete(task)\n finally:\n loop.close()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _get_parser(extra_args):\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n dirs = appdirs.AppDirs('hangups', 'hangups')\n default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt')\n parser.add_argument(\n '--token-path', default=default_token_path,\n help='path used to store OAuth refresh token'\n )\n parser.add_argument(\n '-d', '--debug', action='store_true',\n help='log detailed debugging messages'\n )\n for extra_arg in extra_args:\n parser.add_argument(extra_arg, required=True)\n return parser", "response": "Return an ArgumentParser with any extra arguments."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nrunning the example coroutine.", "response": "async def _async_main(example_coroutine, client, args):\n \"\"\"Run the example coroutine.\"\"\"\n # Spawn a task for hangups to run in parallel with the example coroutine.\n task = asyncio.ensure_future(client.connect())\n\n # Wait for hangups to either finish connecting or raise an exception.\n on_connect = asyncio.Future()\n client.on_connect.add_observer(lambda: on_connect.set_result(None))\n done, _ = await asyncio.wait(\n (on_connect, task), return_when=asyncio.FIRST_COMPLETED\n )\n await asyncio.gather(*done)\n\n # Run the example coroutine. Afterwards, disconnect hangups gracefully and\n # yield the hangups task to handle any exceptions.\n try:\n await example_coroutine(client, args)\n except asyncio.CancelledError:\n pass\n finally:\n await client.disconnect()\n await task"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef print_table(col_tuple, row_tuples):\n col_widths = [max(len(str(row[col])) for row in [col_tuple] + row_tuples)\n for col in range(len(col_tuple))]\n format_str = ' '.join('{{:<{}}}'.format(col_width)\n for col_width in col_widths)\n header_border = ' '.join('=' * col_width for col_width in col_widths)\n print(header_border)\n print(format_str.format(*col_tuple))\n print(header_border)\n for row_tuple in row_tuples:\n print(format_str.format(*row_tuple))\n print(header_border)\n print()", "response": "Print a reStructuredText table."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngenerates a doc for an enum.", "response": "def generate_enum_doc(enum_descriptor, locations, path, name_prefix=''):\n \"\"\"Generate doc for an enum.\n\n Args:\n enum_descriptor: descriptor_pb2.EnumDescriptorProto instance for enum\n to generate docs for.\n locations: Dictionary of location paths tuples to\n descriptor_pb2.SourceCodeInfo.Location instances.\n path: Path tuple to the enum definition.\n name_prefix: Optional prefix for this enum's name.\n \"\"\"\n print(make_subsection(name_prefix + enum_descriptor.name))\n location = locations[path]\n if location.HasField('leading_comments'):\n print(textwrap.dedent(location.leading_comments))\n\n row_tuples = []\n for value_index, value in enumerate(enum_descriptor.value):\n field_location = locations[path + (2, value_index)]\n row_tuples.append((\n make_code(value.name),\n value.number,\n textwrap.fill(get_comment_from_location(field_location), INFINITY),\n ))\n print_table(('Name', 'Number', 'Description'), row_tuples)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef generate_message_doc(message_descriptor, locations, path, name_prefix=''):\n # message_type is 4\n prefixed_name = name_prefix + message_descriptor.name\n print(make_subsection(prefixed_name))\n location = locations[path]\n if location.HasField('leading_comments'):\n print(textwrap.dedent(location.leading_comments))\n\n row_tuples = []\n for field_index, field in enumerate(message_descriptor.field):\n field_location = locations[path + (2, field_index)]\n if field.type not in [11, 14]:\n type_str = TYPE_TO_STR[field.type]\n else:\n type_str = make_link(field.type_name.lstrip('.'))\n row_tuples.append((\n make_code(field.name),\n field.number,\n type_str,\n LABEL_TO_STR[field.label],\n textwrap.fill(get_comment_from_location(field_location), INFINITY),\n ))\n print_table(('Field', 'Number', 'Type', 'Label', 'Description'),\n row_tuples)\n\n # Generate nested messages\n nested_types = enumerate(message_descriptor.nested_type)\n for index, nested_message_desc in nested_types:\n generate_message_doc(nested_message_desc, locations,\n path + (3, index),\n name_prefix=prefixed_name + '.')\n\n # Generate nested enums\n for index, nested_enum_desc in enumerate(message_descriptor.enum_type):\n generate_enum_doc(nested_enum_desc, locations, path + (4, index),\n name_prefix=prefixed_name + '.')", "response": "Generates a documentation for a message and nested messages and enums."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef compile_protofile(proto_file_path):\n out_file = tempfile.mkstemp()[1]\n try:\n subprocess.check_output(['protoc', '--include_source_info',\n '--descriptor_set_out', out_file,\n proto_file_path])\n except subprocess.CalledProcessError as e:\n sys.exit('protoc returned status {}'.format(e.returncode))\n return out_file", "response": "Compile the given proto file to descriptor set."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('protofilepath')\n args = parser.parse_args()\n\n out_file = compile_protofile(args.protofilepath)\n with open(out_file, 'rb') as proto_file:\n # pylint: disable=no-member\n file_descriptor_set = descriptor_pb2.FileDescriptorSet.FromString(\n proto_file.read()\n )\n # pylint: enable=no-member\n\n for file_descriptor in file_descriptor_set.file:\n # Build dict of location tuples\n locations = {}\n for location in file_descriptor.source_code_info.location:\n locations[tuple(location.path)] = location\n # Add comment to top\n print(make_comment('This file was automatically generated from {} and '\n 'should not be edited directly.'\n .format(args.protofilepath)))\n # Generate documentation\n for index, message_desc in enumerate(file_descriptor.message_type):\n generate_message_doc(message_desc, locations, (4, index))\n for index, enum_desc in enumerate(file_descriptor.enum_type):\n generate_enum_doc(enum_desc, locations, (5, index))", "response": "Parse arguments and print generated documentation to stdout."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncreating a directory if it does not exist.", "response": "def dir_maker(path):\n \"\"\"Create a directory if it does not exist.\"\"\"\n directory = os.path.dirname(path)\n if directory != '' and not os.path.isdir(directory):\n try:\n os.makedirs(directory)\n except OSError as e:\n sys.exit('Failed to create directory: {}'.format(e))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef main():\n # Build default paths for files.\n dirs = appdirs.AppDirs('hangups', 'hangups')\n default_log_path = os.path.join(dirs.user_log_dir, 'hangups.log')\n default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt')\n default_config_path = 'hangups.conf'\n user_config_path = os.path.join(dirs.user_config_dir, 'hangups.conf')\n\n # Create a default empty config file if does not exist.\n dir_maker(user_config_path)\n if not os.path.isfile(user_config_path):\n with open(user_config_path, 'a') as cfg:\n cfg.write(\"\")\n\n parser = configargparse.ArgumentParser(\n prog='hangups', default_config_files=[default_config_path,\n user_config_path],\n formatter_class=configargparse.ArgumentDefaultsHelpFormatter,\n add_help=False, # Disable help so we can add it to the correct group.\n )\n general_group = parser.add_argument_group('General')\n general_group.add('-h', '--help', action='help',\n help='show this help message and exit')\n general_group.add('--token-path', default=default_token_path,\n help='path used to store OAuth refresh token')\n general_group.add('--date-format', default='< %y-%m-%d >',\n help='date format string')\n general_group.add('--time-format', default='(%I:%M:%S %p)',\n help='time format string')\n general_group.add('-c', '--config', help='configuration file path',\n is_config_file=True, default=user_config_path)\n general_group.add('-v', '--version', action='version',\n version='hangups {}'.format(hangups.__version__))\n general_group.add('-d', '--debug', action='store_true',\n help='log detailed debugging messages')\n general_group.add('--manual-login', action='store_true',\n help='enable manual login method')\n general_group.add('--log', default=default_log_path, help='log file path')\n key_group = parser.add_argument_group('Keybindings')\n key_group.add('--key-next-tab', default='ctrl d',\n help='keybinding for next tab')\n key_group.add('--key-prev-tab', default='ctrl u',\n help='keybinding for previous tab')\n key_group.add('--key-close-tab', default='ctrl w',\n help='keybinding for close tab')\n key_group.add('--key-quit', default='ctrl e',\n help='keybinding for quitting')\n key_group.add('--key-menu', default='ctrl n',\n help='keybinding for context menu')\n key_group.add('--key-up', default='k',\n help='keybinding for alternate up key')\n key_group.add('--key-down', default='j',\n help='keybinding for alternate down key')\n key_group.add('--key-page-up', default='ctrl b',\n help='keybinding for alternate page up')\n key_group.add('--key-page-down', default='ctrl f',\n help='keybinding for alternate page down')\n notification_group = parser.add_argument_group('Notifications')\n # deprecated in favor of --notification-type=none:\n notification_group.add('-n', '--disable-notifications',\n action='store_true',\n help=configargparse.SUPPRESS)\n notification_group.add('-D', '--discreet-notifications',\n action='store_true',\n help='hide message details in notifications')\n notification_group.add('--notification-type',\n choices=sorted(NOTIFIER_TYPES.keys()),\n default='default',\n help='type of notifications to create')\n\n # add color scheme options\n col_group = parser.add_argument_group('Colors')\n col_group.add('--col-scheme', choices=COL_SCHEMES.keys(),\n default='default', help='colour scheme to use')\n col_group.add('--col-palette-colors', choices=('16', '88', '256'),\n default=16, help='Amount of available colors')\n for name in COL_SCHEME_NAMES:\n col_group.add('--col-' + name.replace('_', '-') + '-fg',\n help=name + ' foreground color')\n col_group.add('--col-' + name.replace('_', '-') + '-bg',\n help=name + ' background color')\n\n args = parser.parse_args()\n\n # Create all necessary directories.\n for path in [args.log, args.token_path]:\n dir_maker(path)\n\n logging.basicConfig(filename=args.log,\n level=logging.DEBUG if args.debug else logging.WARNING,\n format=LOG_FORMAT)\n # urwid makes asyncio's debugging logs VERY noisy, so adjust the log level:\n logging.getLogger('asyncio').setLevel(logging.WARNING)\n\n datetimefmt = {'date': args.date_format,\n 'time': args.time_format}\n\n # setup color scheme\n palette_colors = int(args.col_palette_colors)\n\n col_scheme = COL_SCHEMES[args.col_scheme]\n for name in COL_SCHEME_NAMES:\n col_scheme = add_color_to_scheme(col_scheme, name,\n getattr(args, 'col_' + name + '_fg'),\n getattr(args, 'col_' + name + '_bg'),\n palette_colors)\n\n keybindings = {\n 'next_tab': args.key_next_tab,\n 'prev_tab': args.key_prev_tab,\n 'close_tab': args.key_close_tab,\n 'quit': args.key_quit,\n 'menu': args.key_menu,\n 'up': args.key_up,\n 'down': args.key_down,\n 'page_up': args.key_page_up,\n 'page_down': args.key_page_down,\n }\n\n notifier_ = get_notifier(\n args.notification_type, args.disable_notifications\n )\n\n try:\n ChatUI(\n args.token_path, keybindings, col_scheme, palette_colors,\n datetimefmt, notifier_, args.discreet_notifications,\n args.manual_login\n )\n except KeyboardInterrupt:\n sys.exit('Caught KeyboardInterrupt, exiting abnormally')", "response": "Main entry point for the Hangup CLI."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nhandles exceptions from the asyncio loop.", "response": "def _exception_handler(self, _loop, context):\n \"\"\"Handle exceptions from the asyncio loop.\"\"\"\n # Start a graceful shutdown.\n self._coroutine_queue.put(self._client.disconnect())\n\n # Store the exception to be re-raised later. If the context doesn't\n # contain an exception, create one containing the error message.\n default_exception = Exception(context.get('message'))\n self._exception = context.get('exception', default_exception)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nshows the overlay menu.", "response": "def _show_menu(self):\n \"\"\"Show the overlay menu.\"\"\"\n # If the current widget in the TabbedWindowWidget has a menu,\n # overlay it on the TabbedWindowWidget.\n current_widget = self._tabbed_window.get_current_widget()\n if hasattr(current_widget, 'get_menu_widget'):\n menu_widget = current_widget.get_menu_widget(self._hide_menu)\n overlay = urwid.Overlay(menu_widget, self._tabbed_window,\n align='center', width=('relative', 80),\n valign='middle', height=('relative', 80))\n self._urwid_loop.widget = overlay"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns an existing ConversationWidget or create a new one.", "response": "def get_conv_widget(self, conv_id):\n \"\"\"Return an existing or new ConversationWidget.\"\"\"\n if conv_id not in self._conv_widgets:\n set_title_cb = (lambda widget, title:\n self._tabbed_window.set_tab(widget, title=title))\n widget = ConversationWidget(\n self._client, self._coroutine_queue,\n self._conv_list.get(conv_id), set_title_cb, self._keys,\n self._datetimefmt\n )\n self._conv_widgets[conv_id] = widget\n return self._conv_widgets[conv_id]"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nadding conversation tab if not present and optionally switch to it.", "response": "def add_conversation_tab(self, conv_id, switch=False):\n \"\"\"Add conversation tab if not present, and optionally switch to it.\"\"\"\n conv_widget = self.get_conv_widget(conv_id)\n self._tabbed_window.set_tab(conv_widget, switch=switch,\n title=conv_widget.title)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def _on_connect(self):\n self._user_list, self._conv_list = (\n await hangups.build_user_conversation_list(self._client)\n )\n self._conv_list.on_event.add_observer(self._on_event)\n\n # show the conversation menu\n conv_picker = ConversationPickerWidget(self._conv_list,\n self.on_select_conversation,\n self._keys)\n self._tabbed_window = TabbedWindowWidget(self._keys)\n self._tabbed_window.set_tab(conv_picker, switch=True,\n title='Conversations')\n self._urwid_loop.widget = self._tabbed_window", "response": "Handle connecting for the first time."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nopens conversation tab for new messages & pass events to notifier.", "response": "def _on_event(self, conv_event):\n \"\"\"Open conversation tab for new messages & pass events to notifier.\"\"\"\n conv = self._conv_list.get(conv_event.conversation_id)\n user = conv.get_user(conv_event.user_id)\n show_notification = all((\n isinstance(conv_event, hangups.ChatMessageEvent),\n not user.is_self,\n not conv.is_quiet,\n ))\n if show_notification:\n self.add_conversation_tab(conv_event.conversation_id)\n if self._discreet_notifications:\n notification = DISCREET_NOTIFICATION\n else:\n notification = notifier.Notification(\n user.full_name, get_conv_name(conv), conv_event.text\n )\n self._notifier.send(notification)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nput a coroutine in the queue to be executed.", "response": "def put(self, coro):\n \"\"\"Put a coroutine in the queue to be executed.\"\"\"\n # Avoid logging when a coroutine is queued or executed to avoid log\n # spam from coroutines that are started on every keypress.\n assert asyncio.iscoroutine(coro)\n self._queue.put_nowait(coro)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\nasync def consume(self):\n while True:\n coro = await self._queue.get()\n assert asyncio.iscoroutine(coro)\n await coro", "response": "Consume coroutines from the queue by executing them."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nrename a conversation and call callback.", "response": "def _rename(self, name, callback):\n \"\"\"Rename conversation and call callback.\"\"\"\n self._coroutine_queue.put(self._conversation.rename(name))\n callback()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _on_event(self, _):\n # TODO: handle adding new conversations\n self.sort(key=lambda conv_button: conv_button.last_modified,\n reverse=True)", "response": "Re - order the conversations when an event occurs."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef show_message(self, message_str):\n if self._message_handle is not None:\n self._message_handle.cancel()\n self._message_handle = asyncio.get_event_loop().call_later(\n self._MESSAGE_DELAY_SECS, self._clear_message\n )\n self._message = message_str\n self._update()", "response": "Show a temporary message."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nmake users stop typing when they send a message.", "response": "def _on_event(self, conv_event):\n \"\"\"Make users stop typing when they send a message.\"\"\"\n if isinstance(conv_event, hangups.ChatMessageEvent):\n self._typing_statuses[conv_event.user_id] = (\n hangups.TYPING_TYPE_STOPPED\n )\n self._update()"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nconverts UTC datetime into user interface string.", "response": "def _get_date_str(timestamp, datetimefmt, show_date=False):\n \"\"\"Convert UTC datetime into user interface string.\"\"\"\n fmt = ''\n if show_date:\n fmt += '\\n'+datetimefmt.get('date', '')+'\\n'\n fmt += datetimefmt.get('time', '')\n return timestamp.astimezone(tz=None).strftime(fmt)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef from_conversation_event(conversation, conv_event, prev_conv_event,\n datetimefmt, watermark_users=None):\n \"\"\"Return MessageWidget representing a ConversationEvent.\n\n Returns None if the ConversationEvent does not have a widget\n representation.\n \"\"\"\n user = conversation.get_user(conv_event.user_id)\n # Check whether the previous event occurred on the same day as this\n # event.\n if prev_conv_event is not None:\n is_new_day = (conv_event.timestamp.astimezone(tz=None).date() !=\n prev_conv_event.timestamp.astimezone(tz=None).date())\n else:\n is_new_day = False\n if isinstance(conv_event, hangups.ChatMessageEvent):\n return MessageWidget(conv_event.timestamp, conv_event.text,\n datetimefmt, user, show_date=is_new_day,\n watermark_users=watermark_users)\n elif isinstance(conv_event, hangups.RenameEvent):\n if conv_event.new_name == '':\n text = ('{} cleared the conversation name'\n .format(user.first_name))\n else:\n text = ('{} renamed the conversation to {}'\n .format(user.first_name, conv_event.new_name))\n return MessageWidget(conv_event.timestamp, text, datetimefmt,\n show_date=is_new_day,\n watermark_users=watermark_users)\n elif isinstance(conv_event, hangups.MembershipChangeEvent):\n event_users = [conversation.get_user(user_id) for user_id\n in conv_event.participant_ids]\n names = ', '.join([user.full_name for user in event_users])\n if conv_event.type_ == hangups.MEMBERSHIP_CHANGE_TYPE_JOIN:\n text = ('{} added {} to the conversation'\n .format(user.first_name, names))\n else: # LEAVE\n text = ('{} left the conversation'.format(names))\n return MessageWidget(conv_event.timestamp, text, datetimefmt,\n show_date=is_new_day,\n watermark_users=watermark_users)\n elif isinstance(conv_event, hangups.HangoutEvent):\n text = {\n hangups.HANGOUT_EVENT_TYPE_START: (\n 'A Hangout call is starting.'\n ),\n hangups.HANGOUT_EVENT_TYPE_END: (\n 'A Hangout call ended.'\n ),\n hangups.HANGOUT_EVENT_TYPE_ONGOING: (\n 'A Hangout call is ongoing.'\n ),\n }.get(conv_event.event_type, 'Unknown Hangout call event.')\n return MessageWidget(conv_event.timestamp, text, datetimefmt,\n show_date=is_new_day,\n watermark_users=watermark_users)\n elif isinstance(conv_event, hangups.GroupLinkSharingModificationEvent):\n status_on = hangups.GROUP_LINK_SHARING_STATUS_ON\n status_text = ('on' if conv_event.new_status == status_on\n else 'off')\n text = '{} turned {} joining by link.'.format(user.first_name,\n status_text)\n return MessageWidget(conv_event.timestamp, text, datetimefmt,\n show_date=is_new_day,\n watermark_users=watermark_users)\n else:\n # conv_event is a generic hangups.ConversationEvent.\n text = 'Unknown conversation event'\n return MessageWidget(conv_event.timestamp, text, datetimefmt,\n show_date=is_new_day,\n watermark_users=watermark_users)", "response": "Return a MessageWidget representing a ConversationEvent."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nhandling a new event.", "response": "def _handle_event(self, conv_event):\n \"\"\"Handle updating and scrolling when a new event is added.\n\n Automatically scroll down to show the new text if the bottom is\n showing. This allows the user to scroll up to read previous messages\n while new messages are arriving.\n \"\"\"\n if not self._is_scrolling:\n self.set_focus(conv_event.id_)\n else:\n self._modified()"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nload more events for this conversation.", "response": "async def _load(self):\n \"\"\"Load more events for this conversation.\"\"\"\n try:\n conv_events = await self._conversation.get_events(\n self._conversation.events[0].id_\n )\n except (IndexError, hangups.NetworkError):\n conv_events = []\n if not conv_events:\n self._first_loaded = True\n if self._focus_position == self.POSITION_LOADING and conv_events:\n # If the loading indicator is still focused, and we loaded more\n # events, set focus on the first new event so the loaded\n # indicator is replaced.\n self.set_focus(conv_events[-1].id_)\n else:\n # Otherwise, still need to invalidate in case the loading\n # indicator is showing but not focused.\n self._modified()\n # Loading events can also update the watermarks.\n self._refresh_watermarked_events()\n self._is_loading = False"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn the next or previous position.", "response": "def _get_position(self, position, prev=False):\n \"\"\"Return the next/previous position or raise IndexError.\"\"\"\n if position == self.POSITION_LOADING:\n if prev:\n raise IndexError('Reached last position')\n else:\n return self._conversation.events[0].id_\n else:\n ev = self._conversation.next_event(position, prev=prev)\n if ev is None:\n if prev:\n return self.POSITION_LOADING\n else:\n raise IndexError('Reached first position')\n else:\n return ev.id_"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef set_focus(self, position):\n self._focus_position = position\n self._modified()\n # If we set focus to anywhere but the last position, the user if\n # scrolling up:\n try:\n self.next_position(position)\n except IndexError:\n self._is_scrolling = False\n else:\n self._is_scrolling = True", "response": "Set the focus to position."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_menu_widget(self, close_callback):\n return ConversationMenu(\n self._coroutine_queue, self._conversation, close_callback,\n self._keys\n )", "response": "Return the menu widget associated with this widget."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nhandle marking messages as read and keeping client active.", "response": "def keypress(self, size, key):\n \"\"\"Handle marking messages as read and keeping client active.\"\"\"\n # Set the client as active.\n self._coroutine_queue.put(self._client.set_active())\n\n # Mark the newest event as read.\n self._coroutine_queue.put(self._conversation.update_read_timestamp())\n\n return super().keypress(size, key)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nupdate this conversation s tab title.", "response": "def _set_title(self):\n \"\"\"Update this conversation's tab title.\"\"\"\n self.title = get_conv_name(self._conversation, show_unread=True,\n truncate=True)\n self._set_title_cb(self, self.title)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _on_return(self, text):\n # Ignore if the user hasn't typed a message.\n if not text:\n return\n elif text.startswith('/image') and len(text.split(' ')) == 2:\n # Temporary UI for testing image uploads\n filename = text.split(' ')[1]\n image_file = open(filename, 'rb')\n text = ''\n else:\n image_file = None\n text = replace_emoticons(text)\n segments = hangups.ChatMessageSegment.from_str(text)\n self._coroutine_queue.put(\n self._handle_send_message(\n self._conversation.send_message(\n segments, image_file=image_file\n )\n )\n )", "response": "Called when the user presses return on the send message widget."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nhandles keypresses for changing tabs.", "response": "def keypress(self, size, key):\n \"\"\"Handle keypresses for changing tabs.\"\"\"\n key = super().keypress(size, key)\n num_tabs = len(self._widgets)\n if key == self._keys['prev_tab']:\n self._tab_index = (self._tab_index - 1) % num_tabs\n self._update_tabs()\n elif key == self._keys['next_tab']:\n self._tab_index = (self._tab_index + 1) % num_tabs\n self._update_tabs()\n elif key == self._keys['close_tab']:\n # Don't allow closing the Conversations tab\n if self._tab_index > 0:\n curr_tab = self._widgets[self._tab_index]\n self._widgets.remove(curr_tab)\n del self._widget_title[curr_tab]\n self._tab_index -= 1\n self._update_tabs()\n else:\n return key"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nadd or modify a tab.", "response": "def set_tab(self, widget, switch=False, title=None):\n \"\"\"Add or modify a tab.\n\n If widget is not a tab, it will be added. If switch is True, switch to\n this tab. If title is given, set the tab's title.\n \"\"\"\n if widget not in self._widgets:\n self._widgets.append(widget)\n self._widget_title[widget] = ''\n if switch:\n self._tab_index = self._widgets.index(widget)\n if title:\n self._widget_title[widget] = title\n self._update_tabs()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreplace words with corresponding values in replacements dict.", "response": "def _replace_words(replacements, string):\n \"\"\"Replace words with corresponding values in replacements dict.\n\n Words must be separated by spaces or newlines.\n \"\"\"\n output_lines = []\n for line in string.split('\\n'):\n output_words = []\n for word in line.split(' '):\n new_word = replacements.get(word, word)\n output_words.append(new_word)\n output_lines.append(output_words)\n return '\\n'.join(' '.join(output_words) for output_words in output_lines)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nauthenticating with Google. Args: refresh_token_cache (RefreshTokenCache): Cache to use so subsequent logins may not require credentials. credentials_prompt (CredentialsPrompt): Prompt to use if credentials are required to log in. manual_login (bool): If true, prompt user to log in through a browser and enter authorization code manually. Defaults to false. Returns: dict: Google session cookies. Raises: GoogleAuthError: If authentication with Google fails.", "response": "def get_auth(credentials_prompt, refresh_token_cache, manual_login=False):\n \"\"\"Authenticate with Google.\n\n Args:\n refresh_token_cache (RefreshTokenCache): Cache to use so subsequent\n logins may not require credentials.\n credentials_prompt (CredentialsPrompt): Prompt to use if credentials\n are required to log in.\n manual_login (bool): If true, prompt user to log in through a browser\n and enter authorization code manually. Defaults to false.\n\n Returns:\n dict: Google session cookies.\n\n Raises:\n GoogleAuthError: If authentication with Google fails.\n \"\"\"\n with requests.Session() as session:\n session.headers = {'user-agent': USER_AGENT}\n\n try:\n logger.info('Authenticating with refresh token')\n refresh_token = refresh_token_cache.get()\n if refresh_token is None:\n raise GoogleAuthError(\"Refresh token not found\")\n access_token = _auth_with_refresh_token(session, refresh_token)\n except GoogleAuthError as e:\n logger.info('Failed to authenticate using refresh token: %s', e)\n logger.info('Authenticating with credentials')\n if manual_login:\n authorization_code = (\n credentials_prompt.get_authorization_code()\n )\n else:\n authorization_code = _get_authorization_code(\n session, credentials_prompt\n )\n access_token, refresh_token = _auth_with_code(\n session, authorization_code\n )\n refresh_token_cache.set(refresh_token)\n\n logger.info('Authentication successful')\n return _get_session_cookies(session, access_token)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngets the authorization code using Google account credentials.", "response": "def _get_authorization_code(session, credentials_prompt):\n \"\"\"Get authorization code using Google account credentials.\n\n Because hangups can't use a real embedded browser, it has to use the\n Browser class to enter the user's credentials and retrieve the\n authorization code, which is placed in a cookie. This is the most fragile\n part of the authentication process, because a change to a login form or an\n unexpected prompt could break it.\n\n Raises GoogleAuthError authentication fails.\n\n Returns authorization code string.\n \"\"\"\n browser = Browser(session, OAUTH2_LOGIN_URL)\n\n email = credentials_prompt.get_email()\n browser.submit_form(FORM_SELECTOR, {EMAIL_SELECTOR: email})\n\n password = credentials_prompt.get_password()\n browser.submit_form(FORM_SELECTOR, {PASSWORD_SELECTOR: password})\n\n if browser.has_selector(TOTP_CHALLENGE_SELECTOR):\n browser.submit_form(TOTP_CHALLENGE_SELECTOR, {})\n elif browser.has_selector(PHONE_CHALLENGE_SELECTOR):\n browser.submit_form(PHONE_CHALLENGE_SELECTOR, {})\n\n if browser.has_selector(VERIFICATION_FORM_SELECTOR):\n if browser.has_selector(TOTP_CODE_SELECTOR):\n input_selector = TOTP_CODE_SELECTOR\n elif browser.has_selector(PHONE_CODE_SELECTOR):\n input_selector = PHONE_CODE_SELECTOR\n else:\n raise GoogleAuthError('Unknown verification code input')\n verfification_code = credentials_prompt.get_verification_code()\n browser.submit_form(\n VERIFICATION_FORM_SELECTOR, {input_selector: verfification_code}\n )\n\n try:\n return browser.get_cookie('oauth_code')\n except KeyError:\n raise GoogleAuthError('Authorization code cookie not found')"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nauthenticates using OAuth refresh token.", "response": "def _auth_with_refresh_token(session, refresh_token):\n \"\"\"Authenticate using OAuth refresh token.\n\n Raises GoogleAuthError if authentication fails.\n\n Returns access token string.\n \"\"\"\n # Make a token request.\n token_request_data = {\n 'client_id': OAUTH2_CLIENT_ID,\n 'client_secret': OAUTH2_CLIENT_SECRET,\n 'grant_type': 'refresh_token',\n 'refresh_token': refresh_token,\n }\n res = _make_token_request(session, token_request_data)\n return res['access_token']"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _auth_with_code(session, authorization_code):\n # Make a token request.\n token_request_data = {\n 'client_id': OAUTH2_CLIENT_ID,\n 'client_secret': OAUTH2_CLIENT_SECRET,\n 'code': authorization_code,\n 'grant_type': 'authorization_code',\n 'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',\n }\n res = _make_token_request(session, token_request_data)\n return res['access_token'], res['refresh_token']", "response": "Authenticate using OAuth 2. 0 authorization code. Returns access token and refresh token string."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _make_token_request(session, token_request_data):\n try:\n r = session.post(OAUTH2_TOKEN_REQUEST_URL, data=token_request_data)\n r.raise_for_status()\n except requests.RequestException as e:\n raise GoogleAuthError('Token request failed: {}'.format(e))\n else:\n res = r.json()\n # If an error occurred, a key 'error' will contain an error code.\n if 'error' in res:\n raise GoogleAuthError(\n 'Token request error: {!r}'.format(res['error'])\n )\n return res", "response": "Make OAuth token request."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _get_session_cookies(session, access_token):\n headers = {'Authorization': 'Bearer {}'.format(access_token)}\n\n try:\n r = session.get(('https://accounts.google.com/accounts/OAuthLogin'\n '?source=hangups&issueuberauth=1'), headers=headers)\n r.raise_for_status()\n except requests.RequestException as e:\n raise GoogleAuthError('OAuthLogin request failed: {}'.format(e))\n uberauth = r.text\n\n try:\n r = session.get(('https://accounts.google.com/MergeSession?'\n 'service=mail&'\n 'continue=http://www.google.com&uberauth={}')\n .format(uberauth), headers=headers)\n r.raise_for_status()\n except requests.RequestException as e:\n raise GoogleAuthError('MergeSession request failed: {}'.format(e))\n\n cookies = session.cookies.get_dict(domain='.google.com')\n if cookies == {}:\n raise GoogleAuthError('Failed to find session cookies')\n return cookies", "response": "Use the access token to get session cookies."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get(self):\n logger.info(\n 'Loading refresh_token from %s', repr(self._filename)\n )\n try:\n with open(self._filename) as f:\n return f.read()\n except IOError as e:\n logger.info('Failed to load refresh_token: %s', e)", "response": "Get cached refresh token."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef set(self, refresh_token):\n logger.info('Saving refresh_token to %s', repr(self._filename))\n try:\n with open(self._filename, 'w') as f:\n f.write(refresh_token)\n except IOError as e:\n logger.warning('Failed to save refresh_token: %s', e)", "response": "Set the refresh token for the current user."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\npopulating and submit a form on the current page.", "response": "def submit_form(self, form_selector, input_dict):\n \"\"\"Populate and submit a form on the current page.\n\n Raises GoogleAuthError if form can not be submitted.\n \"\"\"\n logger.info(\n 'Submitting form on page %r', self._page.url.split('?')[0]\n )\n logger.info(\n 'Page contains forms: %s',\n [elem.get('id') for elem in self._page.soup.select('form')]\n )\n try:\n form = self._page.soup.select(form_selector)[0]\n except IndexError:\n raise GoogleAuthError(\n 'Failed to find form {!r} in page'.format(form_selector)\n )\n logger.info(\n 'Page contains inputs: %s',\n [elem.get('id') for elem in form.select('input')]\n )\n for selector, value in input_dict.items():\n try:\n form.select(selector)[0]['value'] = value\n except IndexError:\n raise GoogleAuthError(\n 'Failed to find input {!r} in form'.format(selector)\n )\n try:\n self._page = self._browser.submit(form, self._page.url)\n self._page.raise_for_status()\n except requests.RequestException as e:\n raise GoogleAuthError('Failed to submit form: {}'.format(e))"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _parse_sid_response(res):\n res = json.loads(list(ChunkParser().get_chunks(res))[0])\n sid = res[0][1][1]\n gsessionid = res[1][1][0]['gsid']\n return (sid, gsessionid)", "response": "Parse response format for new channel SID."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_chunks(self, new_data_bytes):\n self._buf += new_data_bytes\n\n while True:\n\n buf_decoded = _best_effort_decode(self._buf)\n buf_utf16 = buf_decoded.encode('utf-16')[2:]\n\n length_str_match = LEN_REGEX.match(buf_decoded)\n if length_str_match is None:\n break\n else:\n length_str = length_str_match.group(1)\n # Both lengths are in number of bytes in UTF-16 encoding.\n # The length of the submission:\n length = int(length_str) * 2\n # The length of the submission length and newline:\n length_length = len((length_str + '\\n').encode('utf-16')[2:])\n if len(buf_utf16) - length_length < length:\n break\n\n submission = buf_utf16[length_length:length_length + length]\n yield submission.decode('utf-16')\n # Drop the length and the submission itself from the beginning\n # of the buffer.\n drop_length = (len((length_str + '\\n').encode()) +\n len(submission.decode('utf-16').encode()))\n self._buf = self._buf[drop_length:]", "response": "Yields the data in the buffer."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nlistening for messages on the backwards channel.", "response": "async def listen(self):\n \"\"\"Listen for messages on the backwards channel.\n\n This method only returns when the connection has been closed due to an\n error.\n \"\"\"\n retries = 0 # Number of retries attempted so far\n need_new_sid = True # whether a new SID is needed\n\n while retries <= self._max_retries:\n # After the first failed retry, back off exponentially longer after\n # each attempt.\n if retries > 0:\n backoff_seconds = self._retry_backoff_base ** retries\n logger.info('Backing off for %s seconds', backoff_seconds)\n await asyncio.sleep(backoff_seconds)\n\n # Request a new SID if we don't have one yet, or the previous one\n # became invalid.\n if need_new_sid:\n await self._fetch_channel_sid()\n need_new_sid = False\n # Clear any previous push data, since if there was an error it\n # could contain garbage.\n self._chunk_parser = ChunkParser()\n try:\n await self._longpoll_request()\n except ChannelSessionError as err:\n logger.warning('Long-polling interrupted: %s', err)\n need_new_sid = True\n except exceptions.NetworkError as err:\n logger.warning('Long-polling request failed: %s', err)\n else:\n # The connection closed successfully, so reset the number of\n # retries.\n retries = 0\n continue\n\n retries += 1\n logger.info('retry attempt count is now %s', retries)\n if self._is_connected:\n self._is_connected = False\n await self.on_disconnect.fire()\n\n # If the request ended with an error, the client must account for\n # messages being dropped during this time.\n\n logger.error('Ran out of retries for long-polling request')"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\nasync def send_maps(self, map_list):\n params = {\n 'VER': 8, # channel protocol version\n 'RID': 81188, # request identifier\n 'ctype': 'hangouts', # client type\n }\n if self._gsessionid_param is not None:\n params['gsessionid'] = self._gsessionid_param\n if self._sid_param is not None:\n params['SID'] = self._sid_param\n data_dict = dict(count=len(map_list), ofs=0)\n for map_num, map_ in enumerate(map_list):\n for map_key, map_val in map_.items():\n data_dict['req{}_{}'.format(map_num, map_key)] = map_val\n res = await self._session.fetch(\n 'post', CHANNEL_URL, params=params, data=data_dict\n )\n return res", "response": "Sends a request to the server containing maps (dicts )."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncreate a new channel for receiving push data.", "response": "async def _fetch_channel_sid(self):\n \"\"\"Creates a new channel for receiving push data.\n\n Sending an empty forward channel request will create a new channel on\n the server.\n\n There's a separate API to get the gsessionid alone that Hangouts for\n Chrome uses, but if we don't send a gsessionid with this request, it\n will return a gsessionid as well as the SID.\n\n Raises hangups.NetworkError if the channel can not be created.\n \"\"\"\n logger.info('Requesting new gsessionid and SID...')\n # Set SID and gsessionid to None so they aren't sent in by send_maps.\n self._sid_param = None\n self._gsessionid_param = None\n res = await self.send_maps([])\n self._sid_param, self._gsessionid_param = _parse_sid_response(res.body)\n logger.info('New SID: {}'.format(self._sid_param))\n logger.info('New gsessionid: {}'.format(self._gsessionid_param))"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\nasync def _longpoll_request(self):\n params = {\n 'VER': 8, # channel protocol version\n 'gsessionid': self._gsessionid_param,\n 'RID': 'rpc', # request identifier\n 't': 1, # trial\n 'SID': self._sid_param, # session ID\n 'CI': 0, # 0 if streaming/chunked requests should be used\n 'ctype': 'hangouts', # client type\n 'TYPE': 'xmlhttp', # type of request\n }\n logger.info('Opening new long-polling request')\n try:\n async with self._session.fetch_raw('GET', CHANNEL_URL,\n params=params) as res:\n\n if res.status != 200:\n if res.status == 400 and res.reason == 'Unknown SID':\n raise ChannelSessionError('SID became invalid')\n raise exceptions.NetworkError(\n 'Request return unexpected status: {}: {}'.format(\n res.status, res.reason))\n\n while True:\n async with async_timeout.timeout(PUSH_TIMEOUT):\n chunk = await res.content.read(MAX_READ_BYTES)\n if not chunk:\n break\n\n await self._on_push_data(chunk)\n\n except asyncio.TimeoutError:\n raise exceptions.NetworkError('Request timed out')\n except aiohttp.ServerDisconnectedError as err:\n raise exceptions.NetworkError(\n 'Server disconnected error: %s' % err)\n except aiohttp.ClientPayloadError:\n raise ChannelSessionError('SID is about to expire')\n except aiohttp.ClientError as err:\n raise exceptions.NetworkError('Request connection error: %s' % err)", "response": "Open a long - polling request and receive arrays."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\nasync def _on_push_data(self, data_bytes):\n logger.debug('Received chunk:\\n{}'.format(data_bytes))\n for chunk in self._chunk_parser.get_chunks(data_bytes):\n\n # Consider the channel connected once the first chunk is received.\n if not self._is_connected:\n if self._on_connect_called:\n self._is_connected = True\n await self.on_reconnect.fire()\n else:\n self._on_connect_called = True\n self._is_connected = True\n await self.on_connect.fire()\n\n # chunk contains a container array\n container_array = json.loads(chunk)\n # container array is an array of inner arrays\n for inner_array in container_array:\n # inner_array always contains 2 elements, the array_id and the\n # data_array.\n array_id, data_array = inner_array\n logger.debug('Chunk contains data array with id %r:\\n%r',\n array_id, data_array)\n await self.on_receive_array.fire(data_array)", "response": "Parse push data and trigger events."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nconstructing a list of ChatMessageSegment objects from a string.", "response": "def from_str(text):\n \"\"\"Construct :class:`ChatMessageSegment` list parsed from a string.\n\n Args:\n text (str): Text to parse. May contain line breaks, URLs and\n formatting markup (simplified Markdown and HTML) to be\n converted into equivalent segments.\n\n Returns:\n List of :class:`ChatMessageSegment` objects.\n \"\"\"\n segment_list = chat_message_parser.parse(text)\n return [ChatMessageSegment(segment.text, **segment.params)\n for segment in segment_list]"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef deserialize(segment):\n link_target = segment.link_data.link_target\n return ChatMessageSegment(\n segment.text, segment_type=segment.type,\n is_bold=segment.formatting.bold,\n is_italic=segment.formatting.italic,\n is_strikethrough=segment.formatting.strikethrough,\n is_underline=segment.formatting.underline,\n link_target=None if link_target == '' else link_target\n )", "response": "Construct a ChatMessageSegment object from a segment."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nserialize this segment to a Hangouts_pb2. Segment message.", "response": "def serialize(self):\n \"\"\"Serialize this segment to a ``Segment`` message.\n\n Returns:\n ``Segment`` message.\n \"\"\"\n segment = hangouts_pb2.Segment(\n type=self.type_,\n text=self.text,\n formatting=hangouts_pb2.Formatting(\n bold=self.is_bold,\n italic=self.is_italic,\n strikethrough=self.is_strikethrough,\n underline=self.is_underline,\n ),\n )\n if self.link_target is not None:\n segment.link_data.link_target = self.link_target\n return segment"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef segments(self):\n seg_list = self._event.chat_message.message_content.segment\n return [ChatMessageSegment.deserialize(seg) for seg in seg_list]", "response": "List of ChatMessageSegment objects in message."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nlist of attachments in the chat message.", "response": "def attachments(self):\n \"\"\"List of attachments in the message (:class:`list`).\"\"\"\n raw_attachments = self._event.chat_message.message_content.attachment\n if raw_attachments is None:\n raw_attachments = []\n attachments = []\n for attachment in raw_attachments:\n for embed_item_type in attachment.embed_item.type:\n known_types = [\n hangouts_pb2.ITEM_TYPE_PLUS_PHOTO,\n hangouts_pb2.ITEM_TYPE_PLACE_V2,\n hangouts_pb2.ITEM_TYPE_PLACE,\n hangouts_pb2.ITEM_TYPE_THING,\n ]\n if embed_item_type not in known_types:\n logger.warning('Received chat message attachment with '\n 'unknown embed type: %r', embed_item_type)\n\n if attachment.embed_item.HasField('plus_photo'):\n attachments.append(\n attachment.embed_item.plus_photo.thumbnail.image_url\n )\n return attachments"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef participant_ids(self):\n return [user.UserID(chat_id=id_.chat_id, gaia_id=id_.gaia_id)\n for id_ in self._event.membership_change.participant_ids]", "response": "Return a list of user. UserID s of users involved in the group."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _decode_field(message, field, value):\n if field.type == FieldDescriptor.TYPE_MESSAGE:\n decode(getattr(message, field.name), value)\n else:\n try:\n if field.type == FieldDescriptor.TYPE_BYTES:\n value = base64.b64decode(value)\n setattr(message, field.name, value)\n except (ValueError, TypeError) as e:\n # ValueError: invalid enum value, negative unsigned int value, or\n # invalid base64\n # TypeError: mismatched type\n logger.warning('Message %r ignoring field %s: %s',\n message.__class__.__name__, field.name, e)", "response": "Decode optional or required field."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ndecode a repeated field.", "response": "def _decode_repeated_field(message, field, value_list):\n \"\"\"Decode repeated field.\"\"\"\n if field.type == FieldDescriptor.TYPE_MESSAGE:\n for value in value_list:\n decode(getattr(message, field.name).add(), value)\n else:\n try:\n for value in value_list:\n if field.type == FieldDescriptor.TYPE_BYTES:\n value = base64.b64decode(value)\n getattr(message, field.name).append(value)\n except (ValueError, TypeError) as e:\n # ValueError: invalid enum value, negative unsigned int value, or\n # invalid base64\n # TypeError: mismatched type\n logger.warning('Message %r ignoring repeated field %s: %s',\n message.__class__.__name__, field.name, e)\n # Ignore any values already decoded by clearing list\n message.ClearField(field.name)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef decode(message, pblite, ignore_first_item=False):\n if not isinstance(pblite, list):\n logger.warning('Ignoring invalid message: expected list, got %r',\n type(pblite))\n return\n if ignore_first_item:\n pblite = pblite[1:]\n # If the last item of the list is a dict, use it as additional field/value\n # mappings. This seems to be an optimization added for dealing with really\n # high field numbers.\n if pblite and isinstance(pblite[-1], dict):\n extra_fields = {int(field_number): value for field_number, value\n in pblite[-1].items()}\n pblite = pblite[:-1]\n else:\n extra_fields = {}\n fields_values = itertools.chain(enumerate(pblite, start=1),\n extra_fields.items())\n for field_number, value in fields_values:\n if value is None:\n continue\n try:\n field = message.DESCRIPTOR.fields_by_number[field_number]\n except KeyError:\n # If the tag number is unknown and the value is non-trivial, log a\n # message to aid reverse-engineering the missing field in the\n # message.\n if value not in [[], '', 0]:\n logger.debug('Message %r contains unknown field %s with value '\n '%r', message.__class__.__name__, field_number,\n value)\n continue\n if field.label == FieldDescriptor.LABEL_REPEATED:\n _decode_repeated_field(message, field, value)\n else:\n _decode_field(message, field, value)", "response": "Decode a Protocol Buffer message into a list of name - value pairs."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef send_private_msg(self, *, user_id, message, auto_escape=False):\n '''\n \u53d1\u9001\u79c1\u804a\u6d88\u606f\n\n ------------\n\n :param int user_id: \u5bf9\u65b9 QQ \u53f7\n :param str | list[ dict[ str, unknown ] ] message: \u8981\u53d1\u9001\u7684\u5185\u5bb9\n :param bool auto_escape: \u6d88\u606f\u5185\u5bb9\u662f\u5426\u4f5c\u4e3a\u7eaf\u6587\u672c\u53d1\u9001\uff08\u5373\u4e0d\u89e3\u6790 CQ \u7801\uff09\uff0c`message` \u6570\u636e\u7c7b\u578b\u4e3a `list` \u65f6\u65e0\u6548\n :return: {\"message_id\": int \u6d88\u606fID}\n :rtype: dict[string, int]\n '''\n return super().__getattr__('send_private_msg') \\\n (user_id=user_id, message=message, auto_escape=auto_escape)", "response": "Send a private message to the user_id."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef send_private_msg_async(self, *, user_id, message, auto_escape=False):\n return super().__getattr__('send_private_msg_async') \\\n (user_id=user_id, message=message, auto_escape=auto_escape)", "response": "Send a private message to the QQ."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nsending a message to a group.", "response": "def send_group_msg(self, *, group_id, message, auto_escape=False):\n \"\"\"\n \u53d1\u9001\u7fa4\u6d88\u606f\n\n ------------\n\n :param int group_id: \u7fa4\u53f7\n :param str | list[ dict[ str, unknown ] ] message: \u8981\u53d1\u9001\u7684\u5185\u5bb9\n :param bool auto_escape: \u6d88\u606f\u5185\u5bb9\u662f\u5426\u4f5c\u4e3a\u7eaf\u6587\u672c\u53d1\u9001\uff08\u5373\u4e0d\u89e3\u6790 CQ \u7801\uff09\uff0c`message` \u6570\u636e\u7c7b\u578b\u4e3a `list` \u65f6\u65e0\u6548\n :return: {\"message_id\": int \u6d88\u606fID}\n :rtype: dict[string, int]\n \"\"\"\n return super().__getattr__('send_group_msg') \\\n (group_id=group_id, message=message, auto_escape=auto_escape)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nsends a message to a group", "response": "def send_group_msg_async(self, *, group_id, message, auto_escape=False):\n \"\"\"\n \u53d1\u9001\u7fa4\u6d88\u606f (\u5f02\u6b65\u7248\u672c)\n\n ------------\n\n :param int group_id: \u7fa4\u53f7\n :param str | list[ dict[ str, unknown ] ] message: \u8981\u53d1\u9001\u7684\u5185\u5bb9\n :param bool auto_escape: \u6d88\u606f\u5185\u5bb9\u662f\u5426\u4f5c\u4e3a\u7eaf\u6587\u672c\u53d1\u9001\uff08\u5373\u4e0d\u89e3\u6790 CQ \u7801\uff09\uff0c`message` \u6570\u636e\u7c7b\u578b\u4e3a `list` \u65f6\u65e0\u6548\n :return: None\n :rtype: None\n \"\"\"\n return super().__getattr__('send_group_msg_async') \\\n (group_id=group_id, message=message, auto_escape=auto_escape)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef send_discuss_msg(self, *, discuss_id, message, auto_escape=False):\n return super().__getattr__('send_discuss_msg') \\\n (discuss_id=discuss_id, message=message, auto_escape=auto_escape)", "response": "send_discuss_msg - Send a discuss message to the server"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef send_msg_async(self, *, message_type, user_id=None, group_id=None, discuss_id=None, message, auto_escape=False):\n return super().__getattr__('send_msg_async') \\\n (message_type=message_type, user_id=user_id, group_id=group_id,\n discuss_id=discuss_id, message=message, auto_escape=auto_escape)", "response": "Send a message to the server."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef send_like(self, *, user_id, times=1):\n return super().__getattr__('send_like') \\\n (user_id=user_id, times=times)", "response": "\u53d1\u9001\u597d\u53cb\u8d5e\n\n ------------\n\n :param int user_id: \u5bf9\u65b9 QQ \u53f7\n :param int times: \u8d5e\u7684\u6b21\u6570\uff0c\u6bcf\u4e2a\u597d\u53cb\u6bcf\u5929\u6700\u591a 10 \u6b21\n :return: None\n :rtype: None"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef set_group_ban(self, *, group_id, user_id, duration=30 * 60):\n return super().__getattr__('set_group_ban') \\\n (group_id=group_id, user_id=user_id, duration=duration)", "response": "\u7fa4\u7ec4\u5355\u4eba\u7981\u8a00\n\n ------------\n\n :param int group_id: \u7fa4\u53f7\n :param int user_id: \u8981\u7981\u8a00\u7684 QQ \u53f7\n :param int duration: \u7981\u8a00\u65f6\u957f\uff0c\u5355\u4f4d\u79d2\uff0c0 \u8868\u793a\u53d6\u6d88\u7981\u8a00\n :return: None\n :rtype: None"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef set_group_anonymous_ban(self, *, group_id, flag, duration=30 * 60):\n return super().__getattr__('set_group_anonymous_ban') \\\n (group_id=group_id, flag=flag, duration=duration)", "response": "Set anonymous ban flag"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef set_group_whole_ban(self, *, group_id, enable=True):\n return super().__getattr__('set_group_whole_ban') \\\n (group_id=group_id, enable=enable)", "response": "Set the whole ban flag for the group."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef set_group_anonymous(self, *, group_id, enable=True):\n return super().__getattr__('set_group_anonymous') \\\n (group_id=group_id, enable=enable)", "response": "Set group anonymous flag"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef set_group_card(self, *, group_id, user_id, card=None):\n return super().__getattr__('set_group_card') \\\n (group_id=group_id, user_id=user_id, card=card)", "response": "Set the group card for a user."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nsetting group_id to None", "response": "def set_group_leave(self, *, group_id, is_dismiss=False):\n \"\"\"\n \u9000\u51fa\u7fa4\u7ec4\n\n ------------\n\n :param int group_id: \u7fa4\u53f7\n :param bool is_dismiss: \u662f\u5426\u89e3\u6563\uff0c\u5982\u679c\u767b\u5f55\u53f7\u662f\u7fa4\u4e3b\uff0c\u5219\u4ec5\u5728\u6b64\u9879\u4e3a true \u65f6\u80fd\u591f\u89e3\u6563\n :return: None\n :rtype: None\n \"\"\"\n return super().__getattr__('set_group_leave') \\\n (group_id=group_id, is_dismiss=is_dismiss)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nsets special title for a group.", "response": "def set_group_special_title(self, *, group_id, user_id, special_title, duration=-1):\n \"\"\"\n \u8bbe\u7f6e\u7fa4\u7ec4\u4e13\u5c5e\u5934\u8854\n\n ------------\n\n :param int group_id: \u7fa4\u53f7\n :param int user_id: \u8981\u8bbe\u7f6e\u7684 QQ \u53f7\n :param str special_title: \u4e13\u5c5e\u5934\u8854\uff0c\u4e0d\u586b\u6216\u7a7a\u5b57\u7b26\u4e32\u8868\u793a\u5220\u9664\u4e13\u5c5e\u5934\u8854\uff0c\u53ea\u80fd\u4fdd\u7559\u524d6\u4e2a\u82f1\u6587\u4e0e\u6c49\u5b57\uff0cEmoji \u6839\u636e\u5b57\u7b26\u5b9e\u9645\u5b57\u7b26\u957f\u5ea6\u5360\u7528\u53ea\u80fd\u653e\u6700\u591a3\u4e2a\u751a\u81f3\u66f4\u5c11\uff0c\u8d85\u51fa\u957f\u5ea6\u90e8\u5206\u4f1a\u88ab\u622a\u65ad\n :param int duration: \u4e13\u5c5e\u5934\u8854\u6709\u6548\u671f\uff0c\u5355\u4f4d\u79d2\uff0c-1 \u8868\u793a\u6c38\u4e45\uff0c\u4e0d\u8fc7\u6b64\u9879\u4f3c\u4e4e\u6ca1\u6709\u6548\u679c\uff0c\u53ef\u80fd\u662f\u53ea\u6709\u67d0\u4e9b\u7279\u6b8a\u7684\u65f6\u95f4\u957f\u5ea6\u6709\u6548\uff0c\u6709\u5f85\u6d4b\u8bd5\n :return: None\n :rtype: None\n \"\"\"\n return super().__getattr__('set_group_special_title') \\\n (group_id=group_id, user_id=user_id, special_title=special_title, duration=duration)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef set_friend_add_request(self, *, flag, approve=True, remark=None):\n return super().__getattr__('set_friend_add_request') \\\n (flag=flag, approve=approve, remark=remark)", "response": "set_friend_add_request - Set the Friend Add Request"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nsets group add request.", "response": "def set_group_add_request(self, *, flag, type, approve=True, reason=None):\n \"\"\"\n \u5904\u7406\u52a0\u7fa4\u8bf7\u6c42\u3001\u7fa4\u7ec4\u6210\u5458\u9080\u8bf7\n\n ------------\n\n :param str flag: \u52a0\u7fa4\u8bf7\u6c42\u7684 flag\uff08\u9700\u4ece\u4e0a\u62a5\u7684\u6570\u636e\u4e2d\u83b7\u5f97\uff09\n :param str type: `add` \u6216 `invite`\uff0c\u8bf7\u6c42\u7c7b\u578b\uff08\u9700\u8981\u548c\u4e0a\u62a5\u6d88\u606f\u4e2d\u7684 `sub_type` \u5b57\u6bb5\u76f8\u7b26\uff09\n :param bool approve: \u662f\u5426\u540c\u610f\u8bf7\u6c42/\u9080\u8bf7\n :param str reason: \u62d2\u7edd\u7406\u7531\uff08\u4ec5\u5728\u62d2\u7edd\u65f6\u6709\u6548\uff09\n :return: None\n :rtype: None\n \"\"\"\n return super().__getattr__('set_group_add_request') \\\n (flag=flag, type=type, approve=approve, reason=reason)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nget group member info.", "response": "def get_group_member_info(self, *, group_id, user_id, no_cache=False):\n \"\"\"\n \u83b7\u53d6\u7fa4\u6210\u5458\u4fe1\u606f\n\n ------------\n\n :param int group_id: \u7fa4\u53f7\n :param int user_id: QQ \u53f7\uff08\u4e0d\u53ef\u4ee5\u662f\u767b\u5f55\u53f7\uff09\n :param bool no_cache: \u662f\u5426\u4e0d\u4f7f\u7528\u7f13\u5b58\uff08\u4f7f\u7528\u7f13\u5b58\u53ef\u80fd\u66f4\u65b0\u4e0d\u53ca\u65f6\uff0c\u4f46\u54cd\u5e94\u66f4\u5feb\uff09\n :return: { \"group_id\": (\u7fa4\u53f7: int), \"user_id\": (QQ \u53f7: int), \"nickname\": (\u6635\u79f0: str), \"card\": (\u7fa4\u540d\u7247/\u5907\u6ce8: str), \"sex\": (\u6027\u522b: str in ['male', 'female', 'unknown']), \"age\": (\u5e74\u9f84: int), \"area\": (\u5730\u533a: str), \"join_time\": (\u52a0\u7fa4\u65f6\u95f4\u6233: int), \"last_sent_time\": (\u6700\u540e\u53d1\u8a00\u65f6\u95f4\u6233: int), \"level\": (\u6210\u5458\u7b49\u7ea7: str), \"role\": (\u89d2\u8272: str in ['owner', 'admin', 'member']), \"unfriendly\": (\u662f\u5426\u4e0d\u826f\u8bb0\u5f55\u6210\u5458: bool), \"title\": (\u4e13\u5c5e\u5934\u8854: str), \"title_expire_time\": (\u4e13\u5c5e\u5934\u8854\u8fc7\u671f\u65f6\u95f4\u6233: int), \"card_changeable\": (\u662f\u5426\u5141\u8bb8\u4fee\u6539\u7fa4\u540d\u7247: bool) }\n :rtype: dict[ str, int | str | bool ]\n\n ------------\n\n ======== =================== ======================================\n \u54cd\u5e94\u6570\u636e\n ---------------------------------------------------------------------\n \u6570\u636e\u7c7b\u578b \u5b57\u6bb5\u540d \u8bf4\u660e\n ======== =================== ======================================\n int group_id \u7fa4\u53f7\n int user_id QQ \u53f7\n str nickname \u6635\u79f0\n str card \u7fa4\u540d\u7247/\u5907\u6ce8\n str sex \u6027\u522b\uff0c`male` \u6216 `female` \u6216 `unknown`\n int age \u5e74\u9f84\n str area \u5730\u533a\n int join_time \u52a0\u7fa4\u65f6\u95f4\u6233\n int last_sent_time \u6700\u540e\u53d1\u8a00\u65f6\u95f4\u6233\n str level \u6210\u5458\u7b49\u7ea7\n str role \u89d2\u8272\uff0c`owner` \u6216 `admin` \u6216 `member`\n bool unfriendly \u662f\u5426\u4e0d\u826f\u8bb0\u5f55\u6210\u5458\n str title \u4e13\u5c5e\u5934\u8854\n int title_expire_time \u4e13\u5c5e\u5934\u8854\u8fc7\u671f\u65f6\u95f4\u6233\n bool card_changeable \u662f\u5426\u5141\u8bb8\u4fee\u6539\u7fa4\u540d\u7247\n ======== =================== ======================================\n \"\"\"\n return super().__getattr__('get_group_member_info') \\\n (group_id=group_id, user_id=user_id, no_cache=no_cache)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_record(self, *, file, out_format):\n return super().__getattr__('get_record') \\\n (file=file, out_format=out_format)", "response": "get_record - Get a record from a file"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nsends a message to the user.", "response": "def send(self, context, message, **kwargs):\n \"\"\"\n \u4fbf\u6377\u56de\u590d\u3002\u4f1a\u6839\u636e\u4f20\u5165\u7684context\u81ea\u52a8\u5224\u65ad\u56de\u590d\u5bf9\u8c61\n ------------\n :param dict context: \u4e8b\u4ef6\u6536\u5230\u7684content\n :return: None\n :rtype: None\n ------------\n \"\"\"\n context = context.copy()\n context['message'] = message\n context.update(kwargs)\n if 'message_type' not in context:\n if 'group_id' in context:\n context['message_type'] = 'group'\n elif 'discuss_id' in context:\n context['message_type'] = 'discuss'\n elif 'user_id' in context:\n context['message_type'] = 'private'\n return super().__getattr__('send_msg')(**context)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a single list of dependencies. For any set returned by toposort(), those items are sorted and appended to the result.", "response": "def toposort_flatten(data, sort=True):\n \"\"\"Returns a single list of dependencies. For any set returned by\ntoposort(), those items are sorted and appended to the result (just to\nmake the results deterministic).\"\"\"\n\n result = []\n for d in toposort(data):\n try:\n result.extend((sorted if sort else list)(d))\n except TypeError as e:\n result.extend(list(d))\n return result"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns a timezone aware datetime if the USE_TZ setting is enabled otherwise the value is returned.", "response": "def _timezone_format(value):\n \"\"\"\n Generates a timezone aware datetime if the 'USE_TZ' setting is enabled\n\n :param value: The datetime value\n :return: A locale aware datetime\n \"\"\"\n return timezone.make_aware(value, timezone.get_current_timezone()) if getattr(settings, 'USE_TZ', False) else value"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef guess_format(self, name):\n name = name.lower()\n faker = self.faker\n if re.findall(r'^is[_A-Z]', name): return lambda x: faker.boolean()\n elif re.findall(r'(_a|A)t$', name): return lambda x: _timezone_format(faker.date_time())\n\n if name in ('first_name', 'firstname', 'first'): return lambda x: faker.first_name()\n if name in ('last_name', 'lastname', 'last'): return lambda x: faker.last_name()\n\n if name in ('username', 'login', 'nickname'): return lambda x:faker.user_name()\n if name in ('email', 'email_address'): return lambda x:faker.email()\n if name in ('phone_number', 'phonenumber', 'phone'): return lambda x:faker.phone_number()\n if name == 'address': return lambda x:faker.address()\n if name == 'city': return lambda x: faker.city()\n if name == 'streetaddress': return lambda x: faker.street_address()\n if name in ('postcode', 'zipcode'): return lambda x: faker.postcode()\n if name == 'state': return lambda x: faker.state()\n if name == 'country': return lambda x: faker.country()\n if name == 'title': return lambda x: faker.sentence()\n if name in ('body', 'summary', 'description'): return lambda x: faker.text()", "response": "Returns a function based on the field s name"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns a function that returns the correct format based on the field type", "response": "def guess_format(self, field):\n \"\"\"\n Returns the correct faker function based on the field type\n :param field:\n \"\"\"\n faker = self.faker\n provider = self.provider\n\n if isinstance(field, DurationField): return lambda x: provider.duration()\n if isinstance(field, UUIDField): return lambda x: provider.uuid()\n\n if isinstance(field, BooleanField): return lambda x: faker.boolean()\n if isinstance(field, NullBooleanField): return lambda x: faker.null_boolean()\n if isinstance(field, PositiveSmallIntegerField): return lambda x: provider.rand_small_int(pos=True)\n if isinstance(field, SmallIntegerField): return lambda x: provider.rand_small_int()\n if isinstance(field, BigIntegerField): return lambda x: provider.rand_big_int()\n if isinstance(field, PositiveIntegerField): return lambda x: provider.rand_small_int(pos=True)\n if isinstance(field, IntegerField): return lambda x: provider.rand_small_int()\n if isinstance(field, FloatField): return lambda x: provider.rand_float()\n if isinstance(field, DecimalField): return lambda x: random.random()\n\n if isinstance(field, URLField): return lambda x: faker.uri()\n if isinstance(field, SlugField): return lambda x: faker.uri_page()\n if isinstance(field, IPAddressField) or isinstance(field, GenericIPAddressField):\n protocol = random.choice(['ipv4','ipv6'])\n return lambda x: getattr(faker, protocol)()\n if isinstance(field, EmailField): return lambda x: faker.email()\n if isinstance(field, CommaSeparatedIntegerField):\n return lambda x: provider.comma_sep_ints()\n\n if isinstance(field, BinaryField): return lambda x: provider.binary()\n if isinstance(field, ImageField): return lambda x: provider.file_name()\n if isinstance(field, FilePathField): return lambda x: provider.file_name()\n if isinstance(field, FileField): return lambda x: provider.file_name()\n\n if isinstance(field, CharField):\n if field.choices:\n return lambda x: random.choice(field.choices)[0]\n return lambda x: faker.text(field.max_length) if field.max_length >= 5 else faker.word()\n if isinstance(field, TextField): return lambda x: faker.text()\n\n if isinstance(field, DateTimeField):\n # format with timezone if it is active\n return lambda x: _timezone_format(faker.date_time())\n if isinstance(field, DateField): return lambda x: faker.date()\n if isinstance(field, TimeField): return lambda x: faker.time()\n raise AttributeError(field)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ngets the formatters for each field using the guessers or related objects fields", "response": "def guess_field_formatters(self, faker):\n \"\"\"\n Gets the formatter methods for each field using the guessers\n or related object fields\n :param faker: Faker factory object\n \"\"\"\n formatters = {}\n name_guesser = NameGuesser(faker)\n field_type_guesser = FieldTypeGuesser(faker)\n\n for field in self.model._meta.fields:\n\n field_name = field.name\n\n if field.get_default(): \n formatters[field_name] = field.get_default()\n continue\n \n if isinstance(field, (ForeignKey, ManyToManyField, OneToOneField)):\n formatters[field_name] = self.build_relation(field, field.related_model)\n continue\n\n if isinstance(field, AutoField):\n continue\n\n if not field.choices:\n formatter = name_guesser.guess_format(field_name)\n if formatter:\n formatters[field_name] = formatter\n continue\n\n formatter = field_type_guesser.guess_format(field)\n if formatter:\n formatters[field_name] = formatter\n continue\n\n return formatters"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nexecutes the stages entities to insert", "response": "def execute(self, using, inserted_entities):\n \"\"\"\n Execute the stages entities to insert\n :param using:\n :param inserted_entities:\n \"\"\"\n\n def format_field(format, inserted_entities):\n if callable(format):\n return format(inserted_entities)\n return format\n\n def turn_off_auto_add(model):\n for field in model._meta.fields:\n if getattr(field, 'auto_now', False):\n field.auto_now = False\n if getattr(field, 'auto_now_add', False):\n field.auto_now_add = False\n\n manager = self.model.objects.db_manager(using=using)\n turn_off_auto_add(manager.model)\n\n faker_data = {\n field: format_field(field_format, inserted_entities)\n for field, field_format in self.field_formatters.items()\n }\n\n # max length restriction check\n for data_field in faker_data:\n field = self.model._meta.get_field(data_field)\n\n if field.max_length and isinstance(faker_data[data_field], str):\n faker_data[data_field] = faker_data[data_field][:field.max_length]\n\n obj = manager.create(**faker_data)\n\n return obj.pk"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nadd an entity to the list of entities and quantities.", "response": "def add_entity(self, model, number, customFieldFormatters=None):\n \"\"\"\n Add an order for the generation of $number records for $entity.\n\n :param model: mixed A Django Model classname,\n or a faker.orm.django.EntitySeeder instance\n :type model: Model\n :param number: int The number of entities to seed\n :type number: integer\n :param customFieldFormatters: optional dict with field as key and \n callable as value\n :type customFieldFormatters: dict or None\n \"\"\"\n if not isinstance(model, ModelSeeder):\n model = ModelSeeder(model)\n\n model.field_formatters = model.guess_field_formatters(self.faker)\n if customFieldFormatters:\n model.field_formatters.update(customFieldFormatters)\n \n klass = model.model\n self.entities[klass] = model\n self.quantities[klass] = number\n self.orders.append(klass)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\npopulating the database using all the Entity classes previously added.", "response": "def execute(self, using=None):\n \"\"\"\n Populate the database using all the Entity classes previously added.\n\n :param using A Django database connection name\n :rtype: A list of the inserted PKs\n \"\"\"\n if not using:\n using = self.get_connection()\n\n inserted_entities = {}\n for klass in self.orders:\n number = self.quantities[klass]\n if klass not in inserted_entities:\n inserted_entities[klass] = []\n for i in range(0, number):\n entity = self.entities[klass].execute(using, inserted_entities)\n inserted_entities[klass].append(entity)\n\n return inserted_entities"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngetting the first connection to the database", "response": "def get_connection(self):\n \"\"\"\n use the first connection available\n :rtype: Connection\n \"\"\"\n\n klass = self.entities.keys()\n if not klass:\n message = 'No classed found. Did you add entities to the Seeder?'\n raise SeederException(message)\n klass = list(klass)[0]\n\n return klass.objects._db"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _read(self, mux, gain, data_rate, mode):\n config = ADS1x15_CONFIG_OS_SINGLE # Go out of power-down mode for conversion.\n # Specify mux value.\n config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET\n # Validate the passed in gain and then set it in the config.\n if gain not in ADS1x15_CONFIG_GAIN:\n raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16')\n config |= ADS1x15_CONFIG_GAIN[gain]\n # Set the mode (continuous or single shot).\n config |= mode\n # Get the default data rate if none is specified (default differs between\n # ADS1015 and ADS1115).\n if data_rate is None:\n data_rate = self._data_rate_default()\n # Set the data rate (this is controlled by the subclass as it differs\n # between ADS1015 and ADS1115).\n config |= self._data_rate_config(data_rate)\n config |= ADS1x15_CONFIG_COMP_QUE_DISABLE # Disble comparator mode.\n # Send the config value to start the ADC conversion.\n # Explicitly break the 16-bit value down to a big endian pair of bytes.\n self._device.writeList(ADS1x15_POINTER_CONFIG, [(config >> 8) & 0xFF, config & 0xFF])\n # Wait for the ADC sample to finish based on the sample rate plus a\n # small offset to be sure (0.1 millisecond).\n time.sleep(1.0/data_rate+0.0001)\n # Retrieve the result.\n result = self._device.readList(ADS1x15_POINTER_CONVERSION, 2)\n return self._conversion_value(result[1], result[0])", "response": "Perform an ADC read with the provided mux gain data_rate and mode."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nperform an ADC read with the provided mux gain data_rate mode high_threshold low_threshold active_low traditional and latching enabled as specified.", "response": "def _read_comparator(self, mux, gain, data_rate, mode, high_threshold,\n low_threshold, active_low, traditional, latching,\n num_readings):\n \"\"\"Perform an ADC read with the provided mux, gain, data_rate, and mode\n values and with the comparator enabled as specified. Returns the signed\n integer result of the read.\n \"\"\"\n assert num_readings == 1 or num_readings == 2 or num_readings == 4, 'Num readings must be 1, 2, or 4!'\n # Set high and low threshold register values.\n self._device.writeList(ADS1x15_POINTER_HIGH_THRESHOLD, [(high_threshold >> 8) & 0xFF, high_threshold & 0xFF])\n self._device.writeList(ADS1x15_POINTER_LOW_THRESHOLD, [(low_threshold >> 8) & 0xFF, low_threshold & 0xFF])\n # Now build up the appropriate config register value.\n config = ADS1x15_CONFIG_OS_SINGLE # Go out of power-down mode for conversion.\n # Specify mux value.\n config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET\n # Validate the passed in gain and then set it in the config.\n if gain not in ADS1x15_CONFIG_GAIN:\n raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16')\n config |= ADS1x15_CONFIG_GAIN[gain]\n # Set the mode (continuous or single shot).\n config |= mode\n # Get the default data rate if none is specified (default differs between\n # ADS1015 and ADS1115).\n if data_rate is None:\n data_rate = self._data_rate_default()\n # Set the data rate (this is controlled by the subclass as it differs\n # between ADS1015 and ADS1115).\n config |= self._data_rate_config(data_rate)\n # Enable window mode if required.\n if not traditional:\n config |= ADS1x15_CONFIG_COMP_WINDOW\n # Enable active high mode if required.\n if not active_low:\n config |= ADS1x15_CONFIG_COMP_ACTIVE_HIGH\n # Enable latching mode if required.\n if latching:\n config |= ADS1x15_CONFIG_COMP_LATCHING\n # Set number of comparator hits before alerting.\n config |= ADS1x15_CONFIG_COMP_QUE[num_readings]\n # Send the config value to start the ADC conversion.\n # Explicitly break the 16-bit value down to a big endian pair of bytes.\n self._device.writeList(ADS1x15_POINTER_CONFIG, [(config >> 8) & 0xFF, config & 0xFF])\n # Wait for the ADC sample to finish based on the sample rate plus a\n # small offset to be sure (0.1 millisecond).\n time.sleep(1.0/data_rate+0.0001)\n # Retrieve the result.\n result = self._device.readList(ADS1x15_POINTER_CONVERSION, 2)\n return self._conversion_value(result[1], result[0])"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef read_adc(self, channel, gain=1, data_rate=None):\n assert 0 <= channel <= 3, 'Channel must be a value within 0-3!'\n # Perform a single shot read and set the mux value to the channel plus\n # the highest bit (bit 3) set.\n return self._read(channel + 0x04, gain, data_rate, ADS1x15_CONFIG_MODE_SINGLE)", "response": "Read a single ADC channel and return the result as a signed integer."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef read_adc_difference(self, differential, gain=1, data_rate=None):\n assert 0 <= differential <= 3, 'Differential must be a value within 0-3!'\n # Perform a single shot read using the provided differential value\n # as the mux value (which will enable differential mode).\n return self._read(differential, gain, data_rate, ADS1x15_CONFIG_MODE_SINGLE)", "response": "Read the difference between two ADC channels and return the ADC value as a signed integer result."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef start_adc_difference(self, differential, gain=1, data_rate=None):\n assert 0 <= differential <= 3, 'Differential must be a value within 0-3!'\n # Perform a single shot read using the provided differential value\n # as the mux value (which will enable differential mode).\n return self._read(differential, gain, data_rate, ADS1x15_CONFIG_MODE_CONTINUOUS)", "response": "Start continuous ADC conversions between two ADC channels."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nstarting continuous ADC conversion on the specified channel.", "response": "def start_adc_comparator(self, channel, high_threshold, low_threshold,\n gain=1, data_rate=None, active_low=True,\n traditional=True, latching=False, num_readings=1):\n \"\"\"Start continuous ADC conversions on the specified channel (0-3) with\n the comparator enabled. When enabled the comparator to will check if\n the ADC value is within the high_threshold & low_threshold value (both\n should be signed 16-bit integers) and trigger the ALERT pin. The\n behavior can be controlled by the following parameters:\n - active_low: Boolean that indicates if ALERT is pulled low or high\n when active/triggered. Default is true, active low.\n - traditional: Boolean that indicates if the comparator is in traditional\n mode where it fires when the value is within the threshold,\n or in window mode where it fires when the value is _outside_\n the threshold range. Default is true, traditional mode.\n - latching: Boolean that indicates if the alert should be held until\n get_last_result() is called to read the value and clear\n the alert. Default is false, non-latching.\n - num_readings: The number of readings that match the comparator before\n triggering the alert. Can be 1, 2, or 4. Default is 1.\n Will return an initial conversion result, then call the get_last_result()\n function continuously to read the most recent conversion result. Call\n stop_adc() to stop conversions.\n \"\"\"\n assert 0 <= channel <= 3, 'Channel must be a value within 0-3!'\n # Start continuous reads with comparator and set the mux value to the\n # channel plus the highest bit (bit 3) set.\n return self._read_comparator(channel + 0x04, gain, data_rate,\n ADS1x15_CONFIG_MODE_CONTINUOUS,\n high_threshold, low_threshold, active_low,\n traditional, latching, num_readings)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef start_adc_difference_comparator(self, differential, high_threshold, low_threshold,\n gain=1, data_rate=None, active_low=True,\n traditional=True, latching=False, num_readings=1):\n \"\"\"Start continuous ADC conversions between two channels with\n the comparator enabled. See start_adc_difference for valid differential\n parameter values and their meaning. When enabled the comparator to will\n check if the ADC value is within the high_threshold & low_threshold value\n (both should be signed 16-bit integers) and trigger the ALERT pin. The\n behavior can be controlled by the following parameters:\n - active_low: Boolean that indicates if ALERT is pulled low or high\n when active/triggered. Default is true, active low.\n - traditional: Boolean that indicates if the comparator is in traditional\n mode where it fires when the value is within the threshold,\n or in window mode where it fires when the value is _outside_\n the threshold range. Default is true, traditional mode.\n - latching: Boolean that indicates if the alert should be held until\n get_last_result() is called to read the value and clear\n the alert. Default is false, non-latching.\n - num_readings: The number of readings that match the comparator before\n triggering the alert. Can be 1, 2, or 4. Default is 1.\n Will return an initial conversion result, then call the get_last_result()\n function continuously to read the most recent conversion result. Call\n stop_adc() to stop conversions.\n \"\"\"\n assert 0 <= differential <= 3, 'Differential must be a value within 0-3!'\n # Start continuous reads with comparator and set the mux value to the\n # channel plus the highest bit (bit 3) set.\n return self._read_comparator(differential, gain, data_rate,\n ADS1x15_CONFIG_MODE_CONTINUOUS,\n high_threshold, low_threshold, active_low,\n traditional, latching, num_readings)", "response": "Start continuous ADC conversions between two channels with the specified differential ADC value high_threshold and low_threshold and trigger the ALERT pin."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreads the last conversion result when in continuous conversion mode. Will return a signed integer value.", "response": "def get_last_result(self):\n \"\"\"Read the last conversion result when in continuous conversion mode.\n Will return a signed integer value.\n \"\"\"\n # Retrieve the conversion register value, convert to a signed int, and\n # return it.\n result = self._device.readList(ADS1x15_POINTER_CONVERSION, 2)\n return self._conversion_value(result[1], result[0])"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nremove all dusty containers with Exited in their status", "response": "def remove_exited_dusty_containers():\n \"\"\"Removed all dusty containers with 'Exited' in their status\"\"\"\n client = get_docker_client()\n exited_containers = get_exited_dusty_containers()\n removed_containers = []\n for container in exited_containers:\n log_to_client(\"Removing container {}\".format(container['Names'][0]))\n try:\n client.remove_container(container['Id'], v=True)\n removed_containers.append(container)\n except Exception as e:\n log_to_client(e.message or str(e))\n return removed_containers"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef remove_images():\n client = get_docker_client()\n removed = _remove_dangling_images()\n dusty_images = get_dusty_images()\n all_images = client.images(all=True)\n for image in all_images:\n if set(image['RepoTags']).intersection(dusty_images):\n try:\n client.remove_image(image['Id'])\n except Exception as e:\n logging.info(\"Couldn't remove image {}\".format(image['RepoTags']))\n else:\n log_to_client(\"Removed Image {}\".format(image['RepoTags']))\n removed.append(image)\n return removed", "response": "Removes all dangling images as well as all images referenced in a dusty spec ; forceful removal is not used"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nupdating the Nginx config with the given config.", "response": "def update_nginx_from_config(nginx_config):\n \"\"\"Write the given config to disk as a Dusty sub-config\n in the Nginx includes directory. Then, either start nginx\n or tell it to reload its config to pick up what we've\n just written.\"\"\"\n logging.info('Updating nginx with new Dusty config')\n temp_dir = tempfile.mkdtemp()\n os.mkdir(os.path.join(temp_dir, 'html'))\n _write_nginx_config(constants.NGINX_BASE_CONFIG, os.path.join(temp_dir, constants.NGINX_PRIMARY_CONFIG_NAME))\n _write_nginx_config(nginx_config['http'], os.path.join(temp_dir, constants.NGINX_HTTP_CONFIG_NAME))\n _write_nginx_config(nginx_config['stream'], os.path.join(temp_dir, constants.NGINX_STREAM_CONFIG_NAME))\n _write_nginx_config(constants.NGINX_502_PAGE_HTML, os.path.join(temp_dir, 'html', constants.NGINX_502_PAGE_NAME))\n sync_local_path_to_vm(temp_dir, constants.NGINX_CONFIG_DIR_IN_VM)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _compose_restart(services):\n\n def _restart_container(client, container):\n log_to_client('Restarting {}'.format(get_canonical_container_name(container)))\n client.restart(container['Id'], timeout=1)\n\n assembled_specs = get_assembled_specs()\n if services == []:\n services = [spec.name for spec in assembled_specs.get_apps_and_services()]\n logging.info('Restarting service containers from list: {}'.format(services))\n client = get_docker_client()\n for service in services:\n container = get_container_for_app_or_service(service, include_exited=True)\n if container is None:\n log_to_client('No container found for {}'.format(service))\n continue\n stopped_linked_containers = _check_stopped_linked_containers(container, assembled_specs)\n if stopped_linked_containers:\n log_to_client('No running containers {0}, which are linked to by {1}. Cannot restart {1}'.format(\n stopped_linked_containers, service))\n else:\n _restart_container(client, container)", "response": "Restarts all containers in the current container tree."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef update_running_containers_from_spec(compose_config, recreate_containers=True):\n write_composefile(compose_config, constants.COMPOSEFILE_PATH)\n compose_up(constants.COMPOSEFILE_PATH, 'dusty', recreate_containers=recreate_containers)", "response": "Takes in a Compose spec file and updates the running containers with the new config."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nresolves a short name to a local version of the object.", "response": "def resolve(cls, all_known_repos, name):\n \"\"\"We require the list of all remote repo paths to be passed in\n to this because otherwise we would need to import the spec assembler\n in this module, which would give us circular imports.\"\"\"\n match = None\n for repo in all_known_repos:\n if repo.remote_path == name: # user passed in a full name\n return repo\n if name == repo.short_name:\n if match is None:\n match = repo\n else:\n raise RuntimeError('Short repo name {} is ambiguous. It matches both {} and {}'.format(name,\n match.remote_path,\n repo.remote_path))\n if match is None:\n raise RuntimeError('Short repo name {} does not match any known repos'.format(name))\n return match"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef ensure_local_repo(self):\n if os.path.exists(self.managed_path):\n logging.debug('Repo {} already exists'.format(self.remote_path))\n return\n\n logging.info('Initiating clone of local repo {}'.format(self.remote_path))\n\n repo_path_parent = parent_dir(self.managed_path)\n if not os.path.exists(repo_path_parent):\n os.makedirs(repo_path_parent)\n with git_error_handling():\n git.Repo.clone_from(self.assemble_remote_path(), self.managed_path)", "response": "Given a Dusty repo object clone the remote into Dusty s local repos\n directory if it does not already exist."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngiving a remote path pull the latest version of the local repo and update the local copy to be up to date.", "response": "def update_local_repo(self, force=False):\n \"\"\"Given a remote path (e.g. github.com/gamechanger/gclib), pull the latest\n commits from master to bring the local copy up to date.\"\"\"\n self.ensure_local_repo()\n\n logging.info('Updating local repo {}'.format(self.remote_path))\n\n managed_repo = git.Repo(self.managed_path)\n with git_error_handling():\n managed_repo.remote().pull('master')\n log_to_client('Updated managed copy of {}'.format(self.remote_path))\n if not self.local_is_up_to_date():\n if force:\n with git_error_handling():\n managed_repo.git.reset('--hard', 'origin/master')\n else:\n log_to_client('WARNING: couldn\\'t update {} because of local conflicts. '\n 'A container may have modified files in the repos\\'s directory. '\n 'Your code generally shouldn\\'t be manipulating the contents of your repo folder - '\n 'please fix this and run `dusty up`'.format(self.managed_path))"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef update_local_repo_async(self, task_queue, force=False):\n self.ensure_local_repo()\n task_queue.enqueue_task(self.update_local_repo, force=force)", "response": "Local repo updating suitable for asynchronous parallel execution."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nchecking if a path exists in the HFS file system.", "response": "def nfs_path_exists(path):\n \"\"\"\n The normal HFS file system that your mac uses does not work the same way\n as the NFS file system. In HFS, capitalization does not matter, but in\n NFS it does. This function checks if a folder exists in HFS file system\n using NFS semantics (case sensitive)\n \"\"\"\n split_path = path.lstrip('/').split('/')\n recreated_path = '/'\n for path_element in split_path:\n if path_element not in os.listdir(recreated_path):\n return False\n recreated_path = \"{}{}/\".format(recreated_path, path_element)\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nupdates the Dusty - managed repos to bring it up to date with the latest master.", "response": "def update_managed_repos(force=False):\n \"\"\"For any active, managed repos, update the Dusty-managed\n copy to bring it up to date with the latest master.\"\"\"\n log_to_client('Pulling latest updates for all active managed repos:')\n update_specs_repo_and_known_hosts()\n repos_to_update = get_all_repos(active_only=True, include_specs_repo=False)\n with parallel_task_queue() as queue:\n log_to_client('Updating managed repos')\n for repo in repos_to_update:\n if not repo.is_overridden:\n repo.update_local_repo_async(queue, force=force)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef prep_for_start_local_env(pull_repos):\n if pull_repos:\n update_managed_repos(force=True)\n assembled_spec = spec_assembler.get_assembled_specs()\n if not assembled_spec[constants.CONFIG_BUNDLES_KEY]:\n raise RuntimeError('No bundles are activated. Use `dusty bundles` to activate bundles before running `dusty up`.')\n virtualbox.initialize_docker_vm()", "response": "Daemon - side command to ensure we re running the latest\n versions of any managed repos including the\n specs repo before we do anything else in the up flow."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef start_local_env(recreate_containers):\n\n assembled_spec = spec_assembler.get_assembled_specs()\n required_absent_assets = virtualbox.required_absent_assets(assembled_spec)\n if required_absent_assets:\n raise RuntimeError('Assets {} are specified as required but are not set. Set them with `dusty assets set`'.format(required_absent_assets))\n\n docker_ip = virtualbox.get_docker_vm_ip()\n\n # Stop will fail if we've never written a Composefile before\n if os.path.exists(constants.COMPOSEFILE_PATH):\n try:\n stop_apps_or_services(rm_containers=recreate_containers)\n except CalledProcessError as e:\n log_to_client(\"WARNING: docker-compose stop failed\")\n log_to_client(str(e))\n\n daemon_warnings.clear_namespace('disk')\n df_info = virtualbox.get_docker_vm_disk_info(as_dict=True)\n if 'M' in df_info['free'] or 'K' in df_info['free']:\n warning_msg = 'VM is low on disk. Available disk: {}'.format(df_info['free'])\n daemon_warnings.warn('disk', warning_msg)\n log_to_client(warning_msg)\n\n log_to_client(\"Compiling together the assembled specs\")\n active_repos = spec_assembler.get_all_repos(active_only=True, include_specs_repo=False)\n log_to_client(\"Compiling the port specs\")\n port_spec = port_spec_compiler.get_port_spec_document(assembled_spec, docker_ip)\n log_to_client(\"Compiling the nginx config\")\n docker_bridge_ip = virtualbox.get_docker_bridge_ip()\n nginx_config = nginx_compiler.get_nginx_configuration_spec(port_spec, docker_bridge_ip)\n log_to_client(\"Creating setup and script bash files\")\n make_up_command_files(assembled_spec, port_spec)\n log_to_client(\"Compiling docker-compose config\")\n compose_config = compose_compiler.get_compose_dict(assembled_spec, port_spec)\n\n log_to_client(\"Saving port forwarding to hosts file\")\n hosts.update_hosts_file_from_port_spec(port_spec)\n log_to_client(\"Configuring NFS\")\n nfs.configure_nfs()\n log_to_client(\"Saving updated nginx config to the VM\")\n nginx.update_nginx_from_config(nginx_config)\n log_to_client(\"Saving Docker Compose config and starting all containers\")\n compose.update_running_containers_from_spec(compose_config, recreate_containers=recreate_containers)\n\n log_to_client(\"Your local environment is now started!\")", "response": "This command will start the local environment and return the current environment."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef stop_apps_or_services(app_or_service_names=None, rm_containers=False):\n if app_or_service_names:\n log_to_client(\"Stopping the following apps or services: {}\".format(', '.join(app_or_service_names)))\n else:\n log_to_client(\"Stopping all running containers associated with Dusty\")\n\n compose.stop_running_services(app_or_service_names)\n if rm_containers:\n compose.rm_containers(app_or_service_names)", "response": "Stops any currently running Docker containers associated with the provided apps_or_services or removes the containers associated with the provided services_or_services. Does not remove the containers associated with the provided apps_or_services."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nrestarting any containers associated with Dusty or associated with the provided app_or_service_names.", "response": "def restart_apps_or_services(app_or_service_names=None):\n \"\"\"Restart any containers associated with Dusty, or associated with\n the provided app_or_service_names.\"\"\"\n if app_or_service_names:\n log_to_client(\"Restarting the following apps or services: {}\".format(', '.join(app_or_service_names)))\n else:\n log_to_client(\"Restarting all active containers associated with Dusty\")\n\n if app_or_service_names:\n specs = spec_assembler.get_assembled_specs()\n specs_list = [specs['apps'][app_name] for app_name in app_or_service_names if app_name in specs['apps']]\n repos = set()\n for spec in specs_list:\n if spec['repo']:\n repos = repos.union(spec_assembler.get_same_container_repos_from_spec(spec))\n nfs.update_nfs_with_repos(repos)\n else:\n nfs.update_nfs_with_repos(spec_assembler.get_all_repos(active_only=True, include_specs_repo=False))\n compose.restart_running_services(app_or_service_names)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning a dictionary containing the Compose spec required to run Dusty s nginx container used for host forwarding.", "response": "def _compose_dict_for_nginx(port_specs):\n \"\"\"Return a dictionary containing the Compose spec required to run\n Dusty's nginx container used for host forwarding.\"\"\"\n spec = {'image': constants.NGINX_IMAGE,\n 'volumes': ['{}:{}'.format(constants.NGINX_CONFIG_DIR_IN_VM, constants.NGINX_CONFIG_DIR_IN_CONTAINER)],\n 'command': 'nginx -g \"daemon off;\" -c /etc/nginx/conf.d/nginx.primary',\n 'container_name': 'dusty_{}_1'.format(constants.DUSTY_NGINX_NAME)}\n all_host_ports = set([nginx_spec['host_port'] for nginx_spec in port_specs['nginx']])\n if all_host_ports:\n spec['ports'] = []\n for port in all_host_ports:\n spec['ports'].append('{0}:{0}'.format(port))\n return {constants.DUSTY_NGINX_NAME: spec}"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get_compose_dict(assembled_specs, port_specs):\n compose_dict = _compose_dict_for_nginx(port_specs)\n for app_name in assembled_specs['apps'].keys():\n compose_dict[app_name] = _composed_app_dict(app_name, assembled_specs, port_specs)\n for service_spec in assembled_specs['services'].values():\n compose_dict[service_spec.name] = _composed_service_dict(service_spec)\n return compose_dict", "response": "This function returns a dictionary representation of a docker - compose. yml file based on assembled_specs and port_specs."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _conditional_links(assembled_specs, app_name):\n link_to_apps = []\n potential_links = assembled_specs['apps'][app_name]['conditional_links']\n for potential_link in potential_links['apps']:\n if potential_link in assembled_specs['apps']:\n link_to_apps.append(potential_link)\n for potential_link in potential_links['services']:\n if potential_link in assembled_specs['services']:\n link_to_apps.append(potential_link)\n return link_to_apps", "response": "Given the assembled specs and app_name this function will return all apps and services specified in the assembled_specs and the app_name s conditional_links property."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the path to the build file for the app.", "response": "def _get_build_path(app_spec):\n \"\"\" Given a spec for an app, returns the value of the `build` field for docker-compose.\n If the path is relative, it is expanded and added to the path of the app's repo. \"\"\"\n if os.path.isabs(app_spec['build']):\n return app_spec['build']\n return os.path.join(Repo(app_spec['repo']).local_path, app_spec['build'])"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _composed_app_dict(app_name, assembled_specs, port_specs):\n logging.info(\"Compose Compiler: Compiling dict for app {}\".format(app_name))\n app_spec = assembled_specs['apps'][app_name]\n compose_dict = app_spec[\"compose\"]\n _apply_env_overrides(env_overrides_for_app_or_service(app_name), compose_dict)\n if 'image' in app_spec and 'build' in app_spec:\n raise RuntimeError(\"image and build are both specified in the spec for {}\".format(app_name))\n elif 'image' in app_spec:\n logging.info\n compose_dict['image'] = app_spec['image']\n elif 'build' in app_spec:\n compose_dict['build'] = _get_build_path(app_spec)\n else:\n raise RuntimeError(\"Neither image nor build was specified in the spec for {}\".format(app_name))\n compose_dict['entrypoint'] = []\n compose_dict['command'] = _compile_docker_command(app_spec)\n compose_dict['container_name'] = \"dusty_{}_1\".format(app_name)\n logging.info(\"Compose Compiler: compiled command {}\".format(compose_dict['command']))\n compose_dict['links'] = _links_for_app(app_spec, assembled_specs)\n logging.info(\"Compose Compiler: links {}\".format(compose_dict['links']))\n compose_dict['volumes'] = compose_dict['volumes'] + _get_compose_volumes(app_name, assembled_specs)\n logging.info(\"Compose Compiler: volumes {}\".format(compose_dict['volumes']))\n port_list = _get_ports_list(app_name, port_specs)\n if port_list:\n compose_dict['ports'] = port_list\n logging.info(\"Compose Compiler: ports {}\".format(port_list))\n compose_dict['user'] = 'root'\n return compose_dict", "response": "This function returns a dictionary of the docker - compose. yml specifications for one app."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _composed_service_dict(service_spec):\n compose_dict = service_spec.plain_dict()\n _apply_env_overrides(env_overrides_for_app_or_service(service_spec.name), compose_dict)\n compose_dict.setdefault('volumes', []).append(_get_cp_volume_mount(service_spec.name))\n compose_dict['container_name'] = \"dusty_{}_1\".format(service_spec.name)\n return compose_dict", "response": "This function returns a dictionary of the docker_compose specifications\n for one service. Currently this is just the Dusty service spec with\n an additional volume mount to support Dusty s cp functionality."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _get_ports_list(app_name, port_specs):\n if app_name not in port_specs['docker_compose']:\n return []\n return [\"{}:{}\".format(port_spec['mapped_host_port'], port_spec['in_container_port'])\n for port_spec in port_specs['docker_compose'][app_name]]", "response": "Returns a list of formatted port mappings for an app"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef validate_specs_from_path(specs_path):\n # Validation of fields with schemer is now down implicitly through get_specs_from_path\n # We are dealing with Dusty_Specs class in this file\n log_to_client(\"Validating specs at path {}\".format(specs_path))\n if not os.path.exists(specs_path):\n raise RuntimeError(\"Specs path not found: {}\".format(specs_path))\n specs = get_specs_from_path(specs_path)\n _check_bare_minimum(specs)\n _validate_spec_names(specs)\n _validate_cycle_free(specs)\n log_to_client(\"Validation Complete!\")", "response": "Validates Dusty specs at the given path."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _env_vars_from_file(filename):\n def split_env(env):\n if '=' in env:\n return env.split('=', 1)\n else:\n return env, None\n env = {}\n for line in open(filename, 'r'):\n line = line.strip()\n if line and not line.startswith('#'):\n k, v = split_env(line)\n env[k] = v\n return env", "response": "This function takes a file and returns a dict of environment variables that can be used to set the environment variables of the current node."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _get_dependent(dependent_type, name, specs, root_spec_type):\n spec = specs[root_spec_type].get(name)\n if spec is None:\n raise RuntimeError(\"{} {} was referenced but not found\".format(root_spec_type, name))\n dependents = spec['depends'][dependent_type]\n all_dependents = set(dependents)\n for dep in dependents:\n all_dependents |= _get_dependent(dependent_type, dep, specs, dependent_type)\n return all_dependents", "response": "Returns all of the dependents of the given name of type dependent_type"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _get_referenced_apps(specs):\n activated_bundles = specs[constants.CONFIG_BUNDLES_KEY].keys()\n all_active_apps = set()\n for active_bundle in activated_bundles:\n bundle_spec = specs[constants.CONFIG_BUNDLES_KEY].get(active_bundle)\n for app_name in bundle_spec['apps']:\n all_active_apps.add(app_name)\n all_active_apps |= _get_dependent('apps', app_name, specs, 'apps')\n return all_active_apps", "response": "Returns a set of all apps that are required to run any bundle in the given specs."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nexpands specs. apps. depends. libs to include any indirectly required libs", "response": "def _expand_libs_in_apps(specs):\n \"\"\"\n Expands specs.apps.depends.libs to include any indirectly required libs\n \"\"\"\n for app_name, app_spec in specs['apps'].iteritems():\n if 'depends' in app_spec and 'libs' in app_spec['depends']:\n app_spec['depends']['libs'] = _get_dependent('libs', app_name, specs, 'apps')"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _expand_libs_in_libs(specs):\n for lib_name, lib_spec in specs['libs'].iteritems():\n if 'depends' in lib_spec and 'libs' in lib_spec['depends']:\n lib_spec['depends']['libs'] = _get_dependent('libs', lib_name, specs, 'libs')", "response": "Expands specs. libs. depends. libs to include any indirectly required libs\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns all libs that are referenced in specs. apps. depends. libs", "response": "def _get_referenced_libs(specs):\n \"\"\"\n Returns all libs that are referenced in specs.apps.depends.libs\n \"\"\"\n active_libs = set()\n for app_spec in specs['apps'].values():\n for lib in app_spec['depends']['libs']:\n active_libs.add(lib)\n return active_libs"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _get_referenced_services(specs):\n active_services = set()\n for app_spec in specs['apps'].values():\n for service in app_spec['depends']['services']:\n active_services.add(service)\n for bundle_spec in specs['bundles'].values():\n for service in bundle_spec['services']:\n active_services.add(service)\n return active_services", "response": "Returns all services that are referenced in the current project."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_repo_of_app_or_library(app_or_library_name):\n specs = get_specs()\n repo_name = specs.get_app_or_lib(app_or_library_name)['repo']\n if not repo_name:\n return None\n return Repo(repo_name)", "response": "This function returns the corresponding Repo object for the given app or library name."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef get_same_container_repos_from_spec(app_or_library_spec):\n repos = set()\n app_or_lib_repo = get_repo_of_app_or_library(app_or_library_spec.name)\n if app_or_lib_repo is not None:\n repos.add(app_or_lib_repo)\n for dependent_name in app_or_library_spec['depends']['libs']:\n repos.add(get_repo_of_app_or_library(dependent_name))\n return repos", "response": "Given a spec of an app or library returns all repos that are guaranteed to live in the same container"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef get_same_container_repos(app_or_library_name):\n specs = get_expanded_libs_specs()\n spec = specs.get_app_or_lib(app_or_library_name)\n return get_same_container_repos_from_spec(spec)", "response": "Given the name of an app or library returns all repos that are guaranteed to live in the same container"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _dusty_hosts_config(hosts_specs):\n rules = ''.join(['{} {}\\n'.format(spec['forwarded_ip'], spec['host_address']) for spec in hosts_specs])\n return config_file.create_config_section(rules)", "response": "Return a string of all host rules required to match the given spec."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef update_hosts_file_from_port_spec(port_spec):\n logging.info('Updating hosts file to match port spec')\n hosts_specs = port_spec['hosts_file']\n current_hosts = config_file.read(constants.HOSTS_PATH)\n cleared_hosts = config_file.remove_current_dusty_config(current_hosts)\n updated_hosts = cleared_hosts + _dusty_hosts_config(hosts_specs)\n config_file.write(constants.HOSTS_PATH, updated_hosts)", "response": "Given a port spec update the hosts file specified at\n constants. HOSTS_PATH with the port mappings specified in the port spec."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nmove the temporary binary to the location of the original binary that s currently being run.", "response": "def _move_temp_binary_to_path(tmp_binary_path):\n \"\"\"Moves the temporary binary to the location of the binary that's currently being run.\n Preserves owner, group, and permissions of original binary\"\"\"\n # pylint: disable=E1101\n binary_path = _get_binary_location()\n if not binary_path.endswith(constants.DUSTY_BINARY_NAME):\n raise RuntimeError('Refusing to overwrite binary {}'.format(binary_path))\n st = os.stat(binary_path)\n permissions = st.st_mode\n owner = st.st_uid\n group = st.st_gid\n shutil.move(tmp_binary_path, binary_path)\n os.chown(binary_path, owner, group)\n os.chmod(binary_path, permissions)\n return binary_path"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _nginx_stream_spec(port_spec, bridge_ip):\n server_string_spec = \"\\t server {\\n\"\n server_string_spec += \"\\t \\t {}\\n\".format(_nginx_listen_string(port_spec))\n server_string_spec += \"\\t \\t {}\\n\".format(_nginx_proxy_string(port_spec, bridge_ip))\n server_string_spec += \"\\t }\\n\"\n return server_string_spec", "response": "This will output the nginx stream config string for specific port spec"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_nginx_configuration_spec(port_spec_dict, docker_bridge_ip):\n nginx_http_config, nginx_stream_config = \"\", \"\"\n for port_spec in port_spec_dict['nginx']:\n if port_spec['type'] == 'http':\n nginx_http_config += _nginx_http_spec(port_spec, docker_bridge_ip)\n elif port_spec['type'] == 'stream':\n nginx_stream_config += _nginx_stream_spec(port_spec, docker_bridge_ip)\n return {'http': nginx_http_config, 'stream': nginx_stream_config}", "response": "This function takes in a port spec dict and returns a nginx configuration string."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef memoized(fn):\n @functools.wraps(fn)\n def memoizer(*args, **kwargs):\n key = function_key(fn) + pickle.dumps(args) + pickle.dumps(_hash_kwargs(kwargs))\n if key not in cache:\n cache[key] = fn(*args, **kwargs)\n return cache[key]\n return memoizer", "response": "Memoized version of the function."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nloads the SSH_AUTH_SOCK environment variable for the user.", "response": "def _load_ssh_auth_post_yosemite(mac_username):\n \"\"\"Starting with Yosemite, launchd was rearchitected and now only one\n launchd process runs for all users. This allows us to much more easily\n impersonate a user through launchd and extract the environment\n variables from their running processes.\"\"\"\n user_id = subprocess.check_output(['id', '-u', mac_username])\n ssh_auth_sock = subprocess.check_output(['launchctl', 'asuser', user_id, 'launchctl', 'getenv', 'SSH_AUTH_SOCK']).rstrip()\n _set_ssh_auth_sock(ssh_auth_sock)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _load_ssh_auth_pre_yosemite():\n for process in psutil.process_iter():\n if process.name() == 'ssh-agent':\n ssh_auth_sock = subprocess.check_output(['launchctl', 'bsexec', str(process.pid), 'launchctl', 'getenv', 'SSH_AUTH_SOCK']).rstrip()\n if ssh_auth_sock:\n _set_ssh_auth_sock(ssh_auth_sock)\n break\n else:\n daemon_warnings.warn('ssh', 'No running ssh-agent found linked to SSH_AUTH_SOCK')", "response": "Load the SSH_AUTH_SOCK environment variable if running on a running ssh - agent."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef check_and_load_ssh_auth():\n\n mac_username = get_config_value(constants.CONFIG_MAC_USERNAME_KEY)\n if not mac_username:\n logging.info(\"Can't setup ssh authorization; no mac_username specified\")\n return\n if not _running_on_mac(): # give our Linux unit tests a way to not freak out\n logging.info(\"Skipping SSH load, we are not running on Mac\")\n return\n\n if _mac_version_is_post_yosemite():\n _load_ssh_auth_post_yosemite(mac_username)\n else:\n _load_ssh_auth_pre_yosemite()", "response": "Checks the user s config value and loads the SSH_AUTH_SOCK environment variable if it is present."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _cleanup_path(path):\n try:\n yield\n finally:\n if os.path.exists(path):\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)", "response": "Recursively delete a path upon exiting this context\n manager. Supports targets that are files or directories. Supports targets that are files or directories."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef copy_between_containers(source_name, source_path, dest_name, dest_path):\n if not container_path_exists(source_name, source_path):\n raise RuntimeError('ERROR: Path {} does not exist inside container {}.'.format(source_path, source_name))\n temp_path = os.path.join(tempfile.mkdtemp(), str(uuid.uuid1()))\n with _cleanup_path(temp_path):\n copy_to_local(temp_path, source_name, source_path, demote=False)\n copy_from_local(temp_path, dest_name, dest_path, demote=False)", "response": "Copy a file from the source container to the destination container."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef copy_from_local(local_path, remote_name, remote_path, demote=True):\n if not os.path.exists(local_path):\n raise RuntimeError('ERROR: Path {} does not exist'.format(local_path))\n temp_identifier = str(uuid.uuid1())\n if os.path.isdir(local_path):\n sync_local_path_to_vm(local_path, os.path.join(vm_cp_path(remote_name), temp_identifier), demote=demote)\n move_dir_inside_container(remote_name, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier), remote_path)\n else:\n sync_local_path_to_vm(local_path, os.path.join(vm_cp_path(remote_name), temp_identifier), demote=demote)\n move_file_inside_container(remote_name, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier), remote_path)", "response": "Copy a path from the local filesystem to a path inside a Dusty\n container."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ncopying a path from inside a Dusty container to a local filesystem.", "response": "def copy_to_local(local_path, remote_name, remote_path, demote=True):\n \"\"\"Copy a path from inside a Dusty container to a path on the\n local filesystem. The path on the local filesystem must be\n wrist-accessible by the user specified in mac_username.\"\"\"\n if not container_path_exists(remote_name, remote_path):\n raise RuntimeError('ERROR: Path {} does not exist inside container {}.'.format(remote_path, remote_name))\n temp_identifier = str(uuid.uuid1())\n copy_path_inside_container(remote_name, remote_path, os.path.join(constants.CONTAINER_CP_DIR, temp_identifier))\n vm_path = os.path.join(vm_cp_path(remote_name), temp_identifier)\n is_dir = vm_path_is_directory(vm_path)\n sync_local_path_from_vm(local_path, vm_path, demote=demote, is_dir=is_dir)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nmounts a nfs repository with the nfs server.", "response": "def _mount_repo(repo, wait_for_server=False):\n \"\"\"\n This function will create the VM directory where a repo will be mounted, if it\n doesn't exist. If wait_for_server is set, it will wait up to 10 seconds for\n the nfs server to start, by retrying mounts that fail with 'Connection Refused'.\n\n If wait_for_server is not set, it will attempt to run the mount command once\n \"\"\"\n check_call_on_vm('sudo mkdir -p {}'.format(repo.vm_path))\n if wait_for_server:\n for i in range(0,10):\n try:\n _run_mount_command(repo)\n return\n except CalledProcessError as e:\n if 'Connection refused' in e.output:\n logging.info('Failed to mount repo; waiting for nfsd to restart')\n time.sleep(1)\n else:\n logging.info(e.output)\n raise e\n log_to_client('Failed to mount repo {}'.format(repo.short_name))\n raise RuntimeError('Unable to mount repo with NFS')\n else:\n _run_mount_command(repo)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngiving a dictionary containing the expanded dusty DAG specs this function will return a dictionary containing the port mappings needed by downstream methods. Currently this includes docker_compose, virtualbox, nginx and hosts_file.", "response": "def get_port_spec_document(expanded_active_specs, docker_vm_ip):\n \"\"\" Given a dictionary containing the expanded dusty DAG specs this function will\n return a dictionary containing the port mappings needed by downstream methods. Currently\n this includes docker_compose, virtualbox, nginx and hosts_file.\"\"\"\n forwarding_port = 65000\n port_spec = {'docker_compose':{}, 'nginx':[], 'hosts_file':[]}\n host_full_addresses, host_names, stream_host_ports = set(), set(), set()\n # No matter the order of apps in expanded_active_specs, we want to produce a consistent\n # port_spec with respect to the apps and the ports they are outputted on\n for app_name in sorted(expanded_active_specs['apps'].keys()):\n app_spec = expanded_active_specs['apps'][app_name]\n if 'host_forwarding' not in app_spec:\n continue\n port_spec['docker_compose'][app_name] = []\n for host_forwarding_spec in app_spec['host_forwarding']:\n # These functions are just used for validating the set of specs all works together\n _add_full_addresses(host_forwarding_spec, host_full_addresses)\n if host_forwarding_spec['type'] == 'stream':\n _add_stream_host_port(host_forwarding_spec, stream_host_ports)\n\n port_spec['docker_compose'][app_name].append(_docker_compose_port_spec(host_forwarding_spec, forwarding_port))\n port_spec['nginx'].append(_nginx_port_spec(host_forwarding_spec, forwarding_port, docker_vm_ip))\n\n _add_host_names(host_forwarding_spec, docker_vm_ip, port_spec, host_names)\n forwarding_port += 1\n return port_spec"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn the Docker registry host associated with a given image name.", "response": "def registry_from_image(image_name):\n \"\"\"Returns the Docker registry host associated with\n a given image name.\"\"\"\n if '/' not in image_name: # official image\n return constants.PUBLIC_DOCKER_REGISTRY\n prefix = image_name.split('/')[0]\n if '.' not in prefix: # user image on official repository, e.g. thieman/clojure\n return constants.PUBLIC_DOCKER_REGISTRY\n return prefix"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_authed_registries():\n result = set()\n if not os.path.exists(constants.DOCKER_CONFIG_PATH):\n return result\n config = json.load(open(constants.DOCKER_CONFIG_PATH, 'r'))\n for registry in config.get('auths', {}).iterkeys():\n try:\n parsed = urlparse(registry)\n except Exception:\n log_to_client('Error parsing registry {} from Docker config, will skip this registry').format(registry)\n # This logic assumes the auth is either of the form\n # gamechanger.io (no scheme, no path after host) or\n # of the form https://index.docker.io/v1/ (scheme,\n # netloc parses correctly, additional path does not matter).\n # These are the formats I saw in my personal config file,\n # not sure what other formats it might accept.\n result.add(parsed.netloc) if parsed.netloc else result.add(parsed.path)\n return result", "response": "Reads the Docker client config file for the current user\n and returns all registries that are authorized by the user."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nputting the client logger into streaming mode.", "response": "def streaming_to_client():\n \"\"\"Puts the client logger into streaming mode, which sends\n unbuffered input through to the socket one character at a time.\n We also disable propagation so the root logger does not\n receive many one-byte emissions. This context handler\n was originally created for streaming Compose up's\n terminal output through to the client and should only be\n used for similarly complex circumstances.\"\"\"\n for handler in client_logger.handlers:\n if hasattr(handler, 'append_newlines'):\n break\n else:\n handler = None\n old_propagate = client_logger.propagate\n client_logger.propagate = False\n if handler is not None:\n old_append = handler.append_newlines\n handler.append_newlines = False\n yield\n client_logger.propagate = old_propagate\n if handler is not None:\n handler.append_newlines = old_append"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef pty_fork(*args):\n\n updated_env = copy(os.environ)\n updated_env.update(get_docker_env())\n args += (updated_env,)\n executable = args[0]\n demote_fn = demote_to_user(get_config_value(constants.CONFIG_MAC_USERNAME_KEY))\n\n child_pid, pty_fd = pty.fork()\n if child_pid == 0:\n demote_fn()\n os.execle(_executable_path(executable), *args)\n else:\n child_process = psutil.Process(child_pid)\n terminal = os.fdopen(pty_fd, 'r', 0)\n with streaming_to_client():\n while child_process.status() == 'running':\n output = terminal.read(1)\n log_to_client(output)\n _, exit_code = os.waitpid(child_pid, 0)\n if exit_code != 0:\n raise subprocess.CalledProcessError(exit_code, ' '.join(args[:-1]))", "response": "Runs a subprocess with a PTY attached via fork and exec."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _compile_docker_commands(app_name, assembled_specs, port_spec):\n app_spec = assembled_specs['apps'][app_name]\n commands = ['set -e']\n commands += _lib_install_commands_for_app(app_name, assembled_specs)\n if app_spec['mount']:\n commands.append(\"cd {}\".format(container_code_path(app_spec)))\n commands.append(\"export PATH=$PATH:{}\".format(container_code_path(app_spec)))\n commands += _copy_assets_commands_for_app(app_spec, assembled_specs)\n commands += _get_once_commands(app_spec, port_spec)\n commands += _get_always_commands(app_spec)\n return commands", "response": "Compile the docker commands for the given app."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nraise the open file handles permitted by the Dusty daemon process and its child processes.", "response": "def _increase_file_handle_limit():\n \"\"\"Raise the open file handles permitted by the Dusty daemon process\n and its child processes. The number we choose here needs to be within\n the OS X default kernel hard limit, which is 10240.\"\"\"\n logging.info('Increasing file handle limit to {}'.format(constants.FILE_HANDLE_LIMIT))\n resource.setrlimit(resource.RLIMIT_NOFILE,\n (constants.FILE_HANDLE_LIMIT, resource.RLIM_INFINITY))"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nstarts the daemon s HTTP server on a separate thread.", "response": "def _start_http_server():\n \"\"\"Start the daemon's HTTP server on a separate thread.\n This server is only used for servicing container status\n requests from Dusty's custom 502 page.\"\"\"\n logging.info('Starting HTTP server at {}:{}'.format(constants.DAEMON_HTTP_BIND_IP,\n constants.DAEMON_HTTP_BIND_PORT))\n thread = threading.Thread(target=http_server.app.run, args=(constants.DAEMON_HTTP_BIND_IP,\n constants.DAEMON_HTTP_BIND_PORT))\n thread.daemon = True\n thread.start()"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_dusty_images():\n specs = get_specs()\n dusty_image_names = [spec['image'] for spec in specs['apps'].values() + specs['services'].values() if 'image' in spec]\n dusty_images = set([name if ':' in name else \"{}:latest\".format(name) for name in dusty_image_names])\n return dusty_images", "response": "Returns all images listed in dusty specs in the form repository : tag."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nripping off and slightly modified based on docker - py s kwargs_from_env utility function.", "response": "def get_docker_client():\n \"\"\"Ripped off and slightly modified based on docker-py's\n kwargs_from_env utility function.\"\"\"\n env = get_docker_env()\n host, cert_path, tls_verify = env['DOCKER_HOST'], env['DOCKER_CERT_PATH'], env['DOCKER_TLS_VERIFY']\n\n params = {'base_url': host.replace('tcp://', 'https://'),\n 'timeout': None,\n 'version': 'auto'}\n if tls_verify and cert_path:\n params['tls'] = docker.tls.TLSConfig(\n client_cert=(os.path.join(cert_path, 'cert.pem'),\n os.path.join(cert_path, 'key.pem')),\n ca_cert=os.path.join(cert_path, 'ca.pem'),\n verify=True,\n ssl_version=None,\n assert_hostname=False)\n return docker.Client(**params)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_dusty_containers(services, include_exited=False):\n client = get_docker_client()\n if services:\n containers = [get_container_for_app_or_service(service, include_exited=include_exited) for service in services]\n return [container for container in containers if container]\n else:\n return [container\n for container in client.containers(all=include_exited)\n if any(name.startswith('/dusty') for name in container.get('Names', []))]", "response": "Get a list of containers associated with the list\n of services. If no services are provided attempts to generate a list of containers associated with Dusty."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef configure_nfs_server():\n repos_for_export = get_all_repos(active_only=True, include_specs_repo=False)\n\n current_exports = _get_current_exports()\n needed_exports = _get_exports_for_repos(repos_for_export)\n\n _ensure_managed_repos_dir_exists()\n\n if not needed_exports.difference(current_exports):\n if not _server_is_running():\n _restart_server()\n return\n\n _write_exports_config(needed_exports)\n _restart_server()", "response": "This function will configure the nfs server with the current exports and the nusty exports needed for all currently active repos."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nensures that the managed repositories directory exists.", "response": "def _ensure_managed_repos_dir_exists():\n \"\"\"\n Our exports file will be invalid if this folder doesn't exist, and the NFS server\n will not run correctly.\n \"\"\"\n if not os.path.exists(constants.REPOS_DIR):\n os.makedirs(constants.REPOS_DIR)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef register_consumer():\n global _consumers\n hostname, port = request.form['hostname'], request.form['port']\n\n app_name = _app_name_from_forwarding_info(hostname, port)\n containers = get_dusty_containers([app_name], include_exited=True)\n if not containers:\n raise ValueError('No container exists for app {}'.format(app_name))\n container = containers[0]\n\n new_id = uuid1()\n new_consumer = Consumer(container['Id'], datetime.utcnow())\n _consumers[str(new_id)] = new_consumer\n\n response = jsonify({'app_name': app_name, 'consumer_id': new_id})\n response.headers['Access-Control-Allow-Origin'] = '*'\n response.headers['Access-Control-Allow-Methods'] = 'GET, POST'\n return response", "response": "Register a consumer for accessing logs from a node."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef consume(consumer_id):\n global _consumers\n consumer = _consumers[consumer_id]\n\n client = get_docker_client()\n try:\n status = client.inspect_container(consumer.container_id)['State']['Status']\n except Exception as e:\n status = 'unknown'\n new_logs = client.logs(consumer.container_id,\n stdout=True,\n stderr=True,\n stream=False,\n timestamps=False,\n since=calendar.timegm(consumer.offset.timetuple()))\n\n updated_consumer = Consumer(consumer.container_id, datetime.utcnow())\n _consumers[str(consumer_id)] = updated_consumer\n\n response = jsonify({'logs': new_logs, 'status': status})\n response.headers['Access-Control-Allow-Origin'] = '*'\n response.headers['Access-Control-Allow-Methods'] = 'GET, POST'\n return response", "response": "Given an existing consumer ID return any new lines from the\n log since the last time the consumer was consumed."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a list of the formatted volume specs for a lib", "response": "def get_lib_volume_mounts(base_lib_name, assembled_specs):\n \"\"\" Returns a list of the formatted volume specs for a lib\"\"\"\n volumes = [_get_lib_repo_volume_mount(assembled_specs['libs'][base_lib_name])]\n volumes.append(get_command_files_volume_mount(base_lib_name, test=True))\n for lib_name in assembled_specs['libs'][base_lib_name]['depends']['libs']:\n lib_spec = assembled_specs['libs'][lib_name]\n volumes.append(_get_lib_repo_volume_mount(lib_spec))\n return volumes"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _get_app_libs_volume_mounts(app_name, assembled_specs):\n volumes = []\n for lib_name in assembled_specs['apps'][app_name]['depends']['libs']:\n lib_spec = assembled_specs['libs'][lib_name]\n volumes.append(\"{}:{}\".format(Repo(lib_spec['repo']).vm_path, container_code_path(lib_spec)))\n return volumes", "response": "Returns a list of the formatted volume mounts for all libs that an app uses."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _dusty_vm_exists():\n existing_vms = check_output_demoted(['VBoxManage', 'list', 'vms'])\n for line in existing_vms.splitlines():\n if '\"{}\"'.format(constants.VM_MACHINE_NAME) in line:\n return True\n return False", "response": "Check if a VM exists in the VBox or Docker Machine."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ninitialize the Dusty VM if it does not already exist.", "response": "def _init_docker_vm():\n \"\"\"Initialize the Dusty VM if it does not already exist.\"\"\"\n if not _dusty_vm_exists():\n log_to_client('Initializing new Dusty VM with Docker Machine')\n machine_options = ['--driver', 'virtualbox',\n '--virtualbox-cpu-count', '-1',\n '--virtualbox-boot2docker-url', constants.CONFIG_BOOT2DOCKER_URL,\n '--virtualbox-memory', str(get_config_value(constants.CONFIG_VM_MEM_SIZE)),\n '--virtualbox-hostonly-nictype', constants.VM_NIC_TYPE]\n check_call_demoted(['docker-machine', 'create'] + machine_options + [constants.VM_MACHINE_NAME],\n redirect_stderr=True)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nstart the Dusty VM if it is not already running.", "response": "def _start_docker_vm():\n \"\"\"Start the Dusty VM if it is not already running.\"\"\"\n is_running = docker_vm_is_running()\n if not is_running:\n log_to_client('Starting docker-machine VM {}'.format(constants.VM_MACHINE_NAME))\n _apply_nat_dns_host_resolver()\n _apply_nat_net_less_greedy_subnet()\n check_and_log_output_and_error_demoted(['docker-machine', 'start', constants.VM_MACHINE_NAME], quiet_on_success=True)\n return is_running"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef docker_vm_is_running():\n running_vms = check_output_demoted(['VBoxManage', 'list', 'runningvms'])\n for line in running_vms.splitlines():\n if '\"{}\"'.format(constants.VM_MACHINE_NAME) in line:\n return True\n return False", "response": "Using VBoxManage is 0. 5 seconds or so faster than Machine."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the MAC address assigned to the host - only adapter using output from VBoxManage.", "response": "def _get_host_only_mac_address():\n \"\"\"Returns the MAC address assigned to the host-only adapter,\n using output from VBoxManage. Returned MAC address has no colons\n and is lower-cased.\"\"\"\n # Get the number of the host-only adapter\n vm_config = _get_vm_config()\n for line in vm_config:\n if line.startswith('hostonlyadapter'):\n adapter_number = int(line[15:16])\n break\n else:\n raise ValueError('No host-only adapter is defined for the Dusty VM')\n\n for line in vm_config:\n if line.startswith('macaddress{}'.format(adapter_number)):\n return line.split('=')[1].strip('\"').lower()\n raise ValueError('Could not find MAC address for adapter number {}'.format(adapter_number))"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _ip_for_mac_from_ip_addr_show(ip_addr_show, target_mac):\n return_next_ip = False\n for line in ip_addr_show.splitlines():\n line = line.strip()\n if line.startswith('link/ether'):\n line_mac = line.split(' ')[1].replace(':', '')\n if line_mac == target_mac:\n return_next_ip = True\n elif return_next_ip and line.startswith('inet') and not line.startswith('inet6'):\n ip = line.split(' ')[1].split('/')[0]\n return ip", "response": "Given a rather - complex output from a ip addr show command returns the IP address that is assigned to the interface with the given MAC."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _get_host_only_ip():\n mac = _get_host_only_mac_address()\n ip_addr_show = check_output_demoted(['ssh', '-o', 'StrictHostKeyChecking=no',\n '-o', 'UserKnownHostsFile=/dev/null',\n '-i', _vm_key_path(), '-p', _get_localhost_ssh_port(),\n 'docker@127.0.0.1', 'ip addr show'])\n return _ip_for_mac_from_ip_addr_show(ip_addr_show, mac)", "response": "Determine the host - only IP of the Dusty VM through Virtualbox and SSH\n directly bypassing Docker Machine."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create_local_copy(cookie_file):\n # if type of cookie_file is a list, use the first element in the list\n if isinstance(cookie_file, list):\n cookie_file = cookie_file[0]\n \n # check if cookie file exists\n if os.path.exists(cookie_file):\n # copy to random name in tmp folder\n tmp_cookie_file = tempfile.NamedTemporaryFile(suffix='.sqlite').name\n open(tmp_cookie_file, 'wb').write(open(cookie_file, 'rb').read())\n return tmp_cookie_file\n else:\n raise BrowserCookieError('Can not find cookie file at: ' + cookie_file)", "response": "Create a local copy of the sqlite cookie database and return the new filename."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef create_cookie(host, path, secure, expires, name, value):\n return http.cookiejar.Cookie(0, name, value, None, False, host, host.startswith('.'), host.startswith('.'), path,\n True, secure, expires, False, None, None, {})", "response": "Shortcut function to create a cookie"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef load(domain_name=\"\"):\n cj = http.cookiejar.CookieJar()\n for cookie_fn in [chrome, firefox]:\n try:\n for cookie in cookie_fn(domain_name=domain_name):\n cj.set_cookie(cookie)\n except BrowserCookieError:\n pass\n return cj", "response": "Try to load cookies from all supported browsers and return a combined cookiejar."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef load(self):\n con = sqlite3.connect(self.tmp_cookie_file)\n cur = con.cursor()\n try:\n # chrome <=55\n cur.execute('SELECT host_key, path, secure, expires_utc, name, value, encrypted_value '\n 'FROM cookies WHERE host_key like \"%{}%\";'.format(self.domain_name))\n except sqlite3.OperationalError:\n # chrome >=56\n cur.execute('SELECT host_key, path, is_secure, expires_utc, name, value, encrypted_value '\n 'FROM cookies WHERE host_key like \"%{}%\";'.format(self.domain_name))\n\n cj = http.cookiejar.CookieJar()\n for item in cur.fetchall():\n host, path, secure, expires, name = item[:5]\n value = self._decrypt(item[5], item[6])\n c = create_cookie(host, path, secure, expires, name, value)\n cj.set_cookie(c)\n con.close()\n return cj", "response": "Load sqlite cookies into a cookiejar"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _randone(d, limit=20, grouprefs=None):\n if grouprefs is None:\n grouprefs = {}\n \"\"\"docstring for _randone\"\"\"\n ret = ''\n for i in d:\n if i[0] == sre_parse.IN:\n ret += choice(_in(i[1]))\n elif i[0] == sre_parse.LITERAL:\n ret += unichr(i[1])\n elif i[0] == sre_parse.CATEGORY:\n ret += choice(CATEGORIES.get(i[1], ['']))\n elif i[0] == sre_parse.ANY:\n ret += choice(CATEGORIES['category_any'])\n elif i[0] == sre_parse.MAX_REPEAT or i[0] == sre_parse.MIN_REPEAT:\n if i[1][1] + 1 - i[1][0] >= limit:\n min, max = i[1][0], i[1][0] + limit - 1\n else:\n min, max = i[1][0], i[1][1]\n for _ in range(randint(min, max)):\n ret += _randone(list(i[1][2]), limit, grouprefs)\n elif i[0] == sre_parse.BRANCH:\n ret += _randone(choice(i[1][1]), limit, grouprefs)\n elif i[0] == sre_parse.SUBPATTERN or i[0] == sre_parse.ASSERT:\n subexpr = i[1][1]\n if IS_PY36_OR_GREATER and i[0] == sre_parse.SUBPATTERN:\n subexpr = i[1][3]\n subp = _randone(subexpr, limit, grouprefs)\n if i[1][0]:\n grouprefs[i[1][0]] = subp\n ret += subp\n elif i[0] == sre_parse.AT:\n continue\n elif i[0] == sre_parse.NOT_LITERAL:\n c = list(CATEGORIES['category_any'])\n if unichr(i[1]) in c:\n c.remove(unichr(i[1]))\n ret += choice(c)\n elif i[0] == sre_parse.GROUPREF:\n ret += grouprefs[i[1]]\n elif i[0] == sre_parse.ASSERT_NOT:\n pass\n else:\n print('[!] cannot handle expression \"%s\"' % str(i))\n\n return ret", "response": "Return a random string from the list d."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef sre_to_string(sre_obj, paren=True):\n ret = u''\n for i in sre_obj:\n if i[0] == sre_parse.IN:\n prefix = ''\n if len(i[1]) and i[1][0][0] == sre_parse.NEGATE:\n prefix = '^'\n ret += u'[{0}{1}]'.format(prefix, sre_to_string(i[1], paren=paren))\n elif i[0] == sre_parse.LITERAL:\n u = unichr(i[1])\n ret += u if u not in sre_parse.SPECIAL_CHARS else '\\\\{0}'.format(u)\n elif i[0] == sre_parse.CATEGORY:\n ret += REVERSE_CATEGORIES[i[1]]\n elif i[0] == sre_parse.ANY:\n ret += '.'\n elif i[0] == sre_parse.BRANCH:\n # TODO simplifications here\n parts = [sre_to_string(x, paren=paren) for x in i[1][1]]\n if not any(parts):\n continue\n if i[1][0]:\n if len(parts) == 1:\n paren = False\n prefix = ''\n else:\n prefix = '?:'\n branch = '|'.join(parts)\n if paren:\n ret += '({0}{1})'.format(prefix, branch)\n else:\n ret += '{0}'.format(branch)\n elif i[0] == sre_parse.SUBPATTERN:\n subexpr = i[1][1]\n if IS_PY36_OR_GREATER and i[0] == sre_parse.SUBPATTERN:\n subexpr = i[1][3]\n if i[1][0]:\n ret += '({0})'.format(sre_to_string(subexpr, paren=False))\n else:\n ret += '{0}'.format(sre_to_string(subexpr, paren=paren))\n elif i[0] == sre_parse.NOT_LITERAL:\n ret += '[^{0}]'.format(unichr(i[1]))\n elif i[0] == sre_parse.MAX_REPEAT:\n if i[1][0] == i[1][1]:\n range_str = '{{{0}}}'.format(i[1][0])\n else:\n if i[1][0] == 0 and i[1][1] - i[1][0] == sre_parse.MAXREPEAT:\n range_str = '*'\n elif i[1][0] == 1 and i[1][1] - i[1][0] == sre_parse.MAXREPEAT - 1:\n range_str = '+'\n else:\n range_str = '{{{0},{1}}}'.format(i[1][0], i[1][1])\n ret += sre_to_string(i[1][2], paren=paren) + range_str\n elif i[0] == sre_parse.MIN_REPEAT:\n if i[1][0] == 0 and i[1][1] == sre_parse.MAXREPEAT:\n range_str = '*?'\n elif i[1][0] == 1 and i[1][1] == sre_parse.MAXREPEAT:\n range_str = '+?'\n elif i[1][1] == sre_parse.MAXREPEAT:\n range_str = '{{{0},}}?'.format(i[1][0])\n else:\n range_str = '{{{0},{1}}}?'.format(i[1][0], i[1][1])\n ret += sre_to_string(i[1][2], paren=paren) + range_str\n elif i[0] == sre_parse.GROUPREF:\n ret += '\\\\{0}'.format(i[1])\n elif i[0] == sre_parse.AT:\n if i[1] == sre_parse.AT_BEGINNING:\n ret += '^'\n elif i[1] == sre_parse.AT_END:\n ret += '$'\n elif i[0] == sre_parse.NEGATE:\n pass\n elif i[0] == sre_parse.RANGE:\n ret += '{0}-{1}'.format(unichr(i[1][0]), unichr(i[1][1]))\n elif i[0] == sre_parse.ASSERT:\n if i[1][0]:\n ret += '(?={0})'.format(sre_to_string(i[1][1], paren=False))\n else:\n ret += '{0}'.format(sre_to_string(i[1][1], paren=paren))\n elif i[0] == sre_parse.ASSERT_NOT:\n pass\n else:\n print('[!] cannot handle expression \"%s\"' % str(i))\n return ret", "response": "Convert a sre_parse object to a string of the n - tuple structure."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef ib64_patched(self, attrsD, contentparams):\n if attrsD.get(\"mode\", \"\") == \"base64\":\n return 0\n if self.contentparams[\"type\"].startswith(\"text/\"):\n return 0\n if self.contentparams[\"type\"].endswith(\"+xml\"):\n return 0\n if self.contentparams[\"type\"].endswith(\"/xml\"):\n return 0\n if self.contentparams[\"type\"].endswith(\"/json\"):\n return 0\n return 0", "response": "Patch isBase64 to prevent Base64 encoding of JSON content\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef cleanwrap(func):\n\n def enc(self, *args, **kwargs):\n \"\"\" Send each item to _cleanup() \"\"\"\n return (func(self, item, **kwargs) for item in args)\n\n return enc", "response": "Wrapper for Zotero. _cleanup\n "}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef ss_wrap(func):\n\n def wrapper(self, *args, **kwargs):\n if not self.savedsearch:\n self.savedsearch = SavedSearch(self)\n return func(self, *args, **kwargs)\n\n return wrapper", "response": "Decorator that ensures that a SavedSearch object exists"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef error_handler(req):\n error_codes = {\n 400: ze.UnsupportedParams,\n 401: ze.UserNotAuthorised,\n 403: ze.UserNotAuthorised,\n 404: ze.ResourceNotFound,\n 409: ze.Conflict,\n 412: ze.PreConditionFailed,\n 413: ze.RequestEntityTooLarge,\n 428: ze.PreConditionRequired,\n 429: ze.TooManyRequests,\n }\n\n def err_msg(req):\n \"\"\" Return a nicely-formatted error message\n \"\"\"\n return \"\\nCode: %s\\nURL: %s\\nMethod: %s\\nResponse: %s\" % (\n req.status_code,\n # error.msg,\n req.url,\n req.request.method,\n req.text,\n )\n\n if error_codes.get(req.status_code):\n # check to see whether its 429\n if req.status_code == 429:\n # call our back-off function\n delay = backoff.delay\n if delay > 32:\n # we've waited a total of 62 seconds (2 + 4 \u2026 + 32), so give up\n backoff.reset()\n raise ze.TooManyRetries(\n \"Continuing to receive HTTP 429 \\\nresponses after 62 seconds. You are being rate-limited, try again later\"\n )\n time.sleep(delay)\n sess = requests.Session()\n new_req = sess.send(req.request)\n try:\n new_req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(new_req)\n else:\n raise error_codes.get(req.status_code)(err_msg(req))\n else:\n raise ze.HTTPError(err_msg(req))", "response": "Error handler for HTTP requests"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef default_headers(self):\n _headers = {\n \"User-Agent\": \"Pyzotero/%s\" % __version__,\n \"Zotero-API-Version\": \"%s\" % __api_version__,\n }\n if self.api_key:\n _headers[\"Authorization\"] = \"Bearer %s\" % self.api_key\n return _headers", "response": "Returns a dictionary of default headers for the current Zotero instance."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nadds a template to the cache for 304 checking accepts a dict and key name adds the retrieval time to self. templates as a new dict using the specified key", "response": "def _cache(self, response, key):\n \"\"\"\n Add a retrieved template to the cache for 304 checking\n accepts a dict and key name, adds the retrieval time, and adds both\n to self.templates as a new dict using the specified key\n \"\"\"\n # cache template and retrieval time for subsequent calls\n thetime = datetime.datetime.utcnow().replace(tzinfo=pytz.timezone(\"GMT\"))\n self.templates[key] = {\"tmplt\": response.json(), \"updated\": thetime}\n return copy.deepcopy(response.json())"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nremoves keys we added for internal use", "response": "def _cleanup(self, to_clean, allow=()):\n \"\"\" Remove keys we added for internal use\n \"\"\"\n # this item's been retrieved from the API, we only need the 'data'\n # entry\n if to_clean.keys() == [\"links\", \"library\", \"version\", \"meta\", \"key\", \"data\"]:\n to_clean = to_clean[\"data\"]\n return dict(\n [\n [k, v]\n for k, v in list(to_clean.items())\n if (k in allow or k not in self.temp_keys)\n ]\n )"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _retrieve_data(self, request=None):\n full_url = \"%s%s\" % (self.endpoint, request)\n # The API doesn't return this any more, so we have to cheat\n self.self_link = request\n self.request = requests.get(url=full_url, headers=self.default_headers())\n self.request.encoding = \"utf-8\"\n try:\n self.request.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(self.request)\n return self.request", "response": "Retrieve Zotero items via the API and return a JSON document containing the Zotero items."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nextracts self first next last links from a request response", "response": "def _extract_links(self):\n \"\"\"\n Extract self, first, next, last links from a request response\n \"\"\"\n extracted = dict()\n try:\n for key, value in self.request.links.items():\n parsed = urlparse(value[\"url\"])\n fragment = \"{path}?{query}\".format(path=parsed[2], query=parsed[4])\n extracted[key] = fragment\n # add a 'self' link\n parsed = list(urlparse(self.self_link))\n # strip 'format' query parameter\n stripped = \"&\".join(\n [\n \"%s=%s\" % (p[0], p[1])\n for p in parse_qsl(parsed[4])\n if p[0] != \"format\"\n ]\n )\n # rebuild url fragment\n # this is a death march\n extracted[\"self\"] = urlunparse(\n [parsed[0], parsed[1], parsed[2], parsed[3], stripped, parsed[5]]\n )\n return extracted\n except KeyError:\n # No links present, because it's a single item\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nchecking if a resource is updated in the library", "response": "def _updated(self, url, payload, template=None):\n \"\"\"\n Generic call to see if a template request returns 304\n accepts:\n - a string to combine with the API endpoint\n - a dict of format values, in case they're required by 'url'\n - a template name to check for\n As per the API docs, a template less than 1 hour old is\n assumed to be fresh, and will immediately return False if found\n \"\"\"\n # If the template is more than an hour old, try a 304\n if (\n abs(\n datetime.datetime.utcnow().replace(tzinfo=pytz.timezone(\"GMT\"))\n - self.templates[template][\"updated\"]\n ).seconds\n > 3600\n ):\n query = self.endpoint + url.format(\n u=self.library_id, t=self.library_type, **payload\n )\n headers = {\n \"If-Modified-Since\": payload[\"updated\"].strftime(\n \"%a, %d %b %Y %H:%M:%S %Z\"\n )\n }\n headers.update(self.default_headers())\n # perform the request, and check whether the response returns 304\n req = requests.get(query, headers=headers)\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return req.status_code == 304\n # Still plenty of life left in't\n return False"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nadd URL parameters to the current object", "response": "def add_parameters(self, **params):\n \"\"\"\n Add URL parameters\n Also ensure that only valid format/content combinations are requested\n \"\"\"\n self.url_params = None\n # we want JSON by default\n if not params.get(\"format\"):\n params[\"format\"] = \"json\"\n # non-standard content must be retrieved as Atom\n if params.get(\"content\"):\n params[\"format\"] = \"atom\"\n # TODO: rewrite format=atom, content=json request\n if \"limit\" not in params or params.get(\"limit\") == 0:\n params[\"limit\"] = 100\n # Need ability to request arbitrary number of results for version\n # response\n # -1 value is hack that works with current version\n elif params[\"limit\"] == -1 or params[\"limit\"] is None:\n del params[\"limit\"]\n # bib format can't have a limit\n if params.get(\"format\") == \"bib\":\n del params[\"limit\"]\n self.url_params = urlencode(params, doseq=True)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nbuild the URL query string for the user key.", "response": "def _build_query(self, query_string, no_params=False):\n \"\"\"\n Set request parameters. Will always add the user ID if it hasn't\n been specifically set by an API method\n \"\"\"\n try:\n query = quote(query_string.format(u=self.library_id, t=self.library_type))\n except KeyError as err:\n raise ze.ParamNotPassed(\"There's a request parameter missing: %s\" % err)\n # Add the URL parameters and the user key, if necessary\n if no_params is False:\n if not self.url_params:\n self.add_parameters()\n query = \"%s?%s\" % (query, self.url_params)\n return query"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns the contents of My Publications", "response": "def publications(self):\n \"\"\" Return the contents of My Publications\n \"\"\"\n if self.library_type != \"users\":\n raise ze.CallDoesNotExist(\n \"This API call does not exist for group libraries\"\n )\n query_string = \"/{t}/{u}/publications/items\"\n return self._build_query(query_string)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef num_collectionitems(self, collection):\n query = \"/{t}/{u}/collections/{c}/items\".format(\n u=self.library_id, t=self.library_type, c=collection.upper()\n )\n return self._totals(query)", "response": "Return the total number of items in the specified collection"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef num_tagitems(self, tag):\n query = \"/{t}/{u}/tags/{ta}/items\".format(\n u=self.library_id, t=self.library_type, ta=tag\n )\n return self._totals(query)", "response": "Return the total number of items for the specified tag"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef key_info(self, **kwargs):\n query_string = \"/keys/{k}\".format(k=self.api_key)\n return self._build_query(query_string)", "response": "Retrieve info about the permissions associated with the given Zotero instance."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef fulltext_item(self, itemkey, **kwargs):\n query_string = \"/{t}/{u}/items/{itemkey}/fulltext\".format(\n t=self.library_type, u=self.library_id, itemkey=itemkey\n )\n return self._build_query(query_string)", "response": "Get full - text content for an item"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef set_fulltext(self, itemkey, payload):\n headers = self.default_headers()\n headers.update({\"Content-Type\": \"application/json\"})\n req = requests.put(\n url=self.endpoint\n + \"/{t}/{u}/items/{k}/fulltext\".format(\n t=self.library_type, u=self.library_id, k=itemkey\n ),\n headers=headers,\n data=json.dumps(payload),\n )\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return True", "response": "Set full - text data for an itemkey."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef new_fulltext(self, version):\n query_string = \"/{t}/{u}/fulltext\".format(\n t=self.library_type, u=self.library_id\n )\n headers = {\"since\": str(version)}\n headers.update(self.default_headers())\n req = requests.get(self.endpoint + query_string, headers=headers)\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return req.json()", "response": "Retrieve list of full - text content items and versions which are newer\n than version."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngets the last modified version of the resource.", "response": "def last_modified_version(self, **kwargs):\n \"\"\" Get the last modified version\n \"\"\"\n self.items(**kwargs)\n return int(self.request.headers.get(\"last-modified-version\", 0))"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef file(self, item, **kwargs):\n query_string = \"/{t}/{u}/items/{i}/file\".format(\n u=self.library_id, t=self.library_type, i=item.upper()\n )\n return self._build_query(query_string, no_params=True)", "response": "Get the file from an specific item"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef dump(self, itemkey, filename=None, path=None):\n if not filename:\n filename = self.item(itemkey)[\"data\"][\"filename\"]\n if path:\n pth = os.path.join(path, filename)\n else:\n pth = filename\n file = self.file(itemkey)\n if self.snapshot:\n self.snapshot = False\n pth = pth + \".zip\"\n with open(pth, \"wb\") as f:\n f.write(file)", "response": "Dump a file attachment to disk with optional filename and path."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting all the subcollections of a specific collection", "response": "def collections_sub(self, collection, **kwargs):\n \"\"\" Get subcollections for a specific collection\n \"\"\"\n query_string = \"/{t}/{u}/collections/{c}/collections\".format(\n u=self.library_id, t=self.library_type, c=collection.upper()\n )\n return self._build_query(query_string)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngetting tags for the current user", "response": "def tags(self, **kwargs):\n \"\"\" Get tags\n \"\"\"\n query_string = \"/{t}/{u}/tags\"\n self.tag_data = True\n return self._build_query(query_string)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\niterating over the next set of links.", "response": "def iterfollow(self):\n \"\"\" Generator for self.follow()\n \"\"\"\n # use same criterion as self.follow()\n if self.links is None:\n return\n if self.links.get(\"next\"):\n yield self.follow()\n else:\n raise StopIteration"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef everything(self, query):\n try:\n items = []\n items.extend(query)\n while self.links.get(\"next\"):\n items.extend(self.follow())\n except TypeError:\n # we have a bibliography object ughh\n items = copy.deepcopy(query)\n while self.links.get(\"next\"):\n items.entries.extend(self.follow().entries)\n return items", "response": "Retrieve all items in the library for a particular query"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_subset(self, subset):\n if len(subset) > 50:\n raise ze.TooManyItems(\"You may only retrieve 50 items per call\")\n # remember any url parameters that have been set\n params = self.url_params\n retr = []\n for itm in subset:\n retr.extend(self.item(itm))\n self.url_params = params\n # clean up URL params when we're finished\n self.url_params = None\n return retr", "response": "Retrieve a subset of items from the cache"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nprocesses the JSON data returned by the API call.", "response": "def _json_processor(self, retrieved):\n \"\"\" Format and return data from API calls which return Items\n \"\"\"\n json_kwargs = {}\n if self.preserve_json_order:\n json_kwargs[\"object_pairs_hook\"] = OrderedDict\n # send entries to _tags_data if there's no JSON\n try:\n items = [\n json.loads(e[\"content\"][0][\"value\"], **json_kwargs)\n for e in retrieved.entries\n ]\n except KeyError:\n return self._tags_data(retrieved)\n return items"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning a list of dicts which are dumped CSL JSON", "response": "def _csljson_processor(self, retrieved):\n \"\"\" Return a list of dicts which are dumped CSL JSON\n \"\"\"\n items = []\n json_kwargs = {}\n if self.preserve_json_order:\n json_kwargs[\"object_pairs_hook\"] = OrderedDict\n for csl in retrieved.entries:\n items.append(json.loads(csl[\"content\"][0][\"value\"], **json_kwargs))\n self.url_params = None\n return items"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a list of strings formatted as HTML bibliography entries", "response": "def _bib_processor(self, retrieved):\n \"\"\" Return a list of strings formatted as HTML bibliography entries\n \"\"\"\n items = []\n for bib in retrieved.entries:\n items.append(bib[\"content\"][0][\"value\"])\n self.url_params = None\n return items"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn a list of strings formatted as HTML citation entries", "response": "def _citation_processor(self, retrieved):\n \"\"\" Return a list of strings formatted as HTML citation entries\n \"\"\"\n items = []\n for cit in retrieved.entries:\n items.append(cit[\"content\"][0][\"value\"])\n self.url_params = None\n return items"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef item_template(self, itemtype):\n # if we have a template and it hasn't been updated since we stored it\n template_name = \"item_template_\" + itemtype\n query_string = \"/items/new?itemType={i}\".format(i=itemtype)\n if self.templates.get(template_name) and not self._updated(\n query_string, self.templates[template_name], template_name\n ):\n return copy.deepcopy(self.templates[template_name][\"tmplt\"])\n # otherwise perform a normal request and cache the response\n retrieved = self._retrieve_data(query_string)\n return self._cache(retrieved, template_name)", "response": "Get a template for a new item type"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _attachment(self, payload, parentid=None):\n attachment = Zupload(self, payload, parentid)\n res = attachment.upload()\n return res", "response": "Create attachments with the given payload and parentid."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef show_condition_operators(self, condition):\n # dict keys of allowed operators for the current condition\n permitted_operators = self.savedsearch.conditions_operators.get(condition)\n # transform these into values\n permitted_operators_list = set(\n [self.savedsearch.operators.get(op) for op in permitted_operators]\n )\n return permitted_operators_list", "response": "Show available operators for a given saved search condition"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef saved_search(self, name, conditions):\n self.savedsearch._validate(conditions)\n payload = [{\"name\": name, \"conditions\": conditions}]\n headers = {\"Zotero-Write-Token\": token()}\n headers.update(self.default_headers())\n req = requests.post(\n url=self.endpoint\n + \"/{t}/{u}/searches\".format(t=self.library_type, u=self.library_id),\n headers=headers,\n data=json.dumps(payload),\n )\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return req.json()", "response": "Create a saved search for the given name and conditions."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef delete_saved_search(self, keys):\n headers = {\"Zotero-Write-Token\": token()}\n headers.update(self.default_headers())\n req = requests.delete(\n url=self.endpoint\n + \"/{t}/{u}/searches\".format(t=self.library_type, u=self.library_id),\n headers=headers,\n params={\"searchKey\": \",\".join(keys)},\n )\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return req.status_code", "response": "Delete one or more saved searches by passing a list of one or more unique search keys\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nuploads files to the already created attachments", "response": "def upload_attachments(self, attachments, parentid=None, basedir=None):\n \"\"\"Upload files to the already created (but never uploaded) attachments\"\"\"\n return Zupload(self, attachments, parentid, basedir=basedir).upload()"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nadds one or more tags to an item and updates it on the server", "response": "def add_tags(self, item, *tags):\n \"\"\"\n Add one or more tags to a retrieved item,\n then update it on the server\n Accepts a dict, and one or more tags to add to it\n Returns the updated item from the server\n \"\"\"\n # Make sure there's a tags field, or add one\n try:\n assert item[\"data\"][\"tags\"]\n except AssertionError:\n item[\"data\"][\"tags\"] = list()\n for tag in tags:\n item[\"data\"][\"tags\"].append({\"tag\": \"%s\" % tag})\n # make sure everything's OK\n assert self.check_items([item])\n return self.update_item(item)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nchecks that the items to be created contain no invalid dict keys.", "response": "def check_items(self, items):\n \"\"\"\n Check that items to be created contain no invalid dict keys\n Accepts a single argument: a list of one or more dicts\n The retrieved fields are cached and re-used until a 304 call fails\n \"\"\"\n # check for a valid cached version\n if self.templates.get(\"item_fields\") and not self._updated(\n \"/itemFields\", self.templates[\"item_fields\"], \"item_fields\"\n ):\n template = set(t[\"field\"] for t in self.templates[\"item_fields\"][\"tmplt\"])\n else:\n template = set(t[\"field\"] for t in self.item_fields())\n # add fields we know to be OK\n template = template | set(\n [\n \"path\",\n \"tags\",\n \"notes\",\n \"itemType\",\n \"creators\",\n \"mimeType\",\n \"linkMode\",\n \"note\",\n \"charset\",\n \"dateAdded\",\n \"version\",\n \"collections\",\n \"dateModified\",\n \"relations\",\n # attachment items\n \"parentItem\",\n \"mtime\",\n \"contentType\",\n \"md5\",\n \"filename\",\n ]\n )\n template = template | set(self.temp_keys)\n for pos, item in enumerate(items):\n if set(item) == set([\"links\", \"library\", \"version\", \"meta\", \"key\", \"data\"]):\n # we have an item that was retrieved from the API\n item = item[\"data\"]\n to_check = set(i for i in list(item.keys()))\n difference = to_check.difference(template)\n if difference:\n raise ze.InvalidItemFields(\n \"Invalid keys present in item %s: %s\"\n % (pos + 1, \" \".join(i for i in difference))\n )\n return items"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef fields_types(self, tname, qstring, itemtype):\n # check for a valid cached version\n template_name = tname + itemtype\n query_string = qstring.format(i=itemtype)\n if self.templates.get(template_name) and not self._updated(\n query_string, self.templates[template_name], template_name\n ):\n return self.templates[template_name][\"tmplt\"]\n # otherwise perform a normal request and cache the response\n retrieved = self._retrieve_data(query_string)\n return self._cache(retrieved, template_name)", "response": "Retrieve item fields or creator types"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting all available item fields", "response": "def item_fields(self):\n \"\"\" Get all available item fields\n \"\"\"\n # Check for a valid cached version\n if self.templates.get(\"item_fields\") and not self._updated(\n \"/itemFields\", self.templates[\"item_fields\"], \"item_fields\"\n ):\n return self.templates[\"item_fields\"][\"tmplt\"]\n query_string = \"/itemFields\"\n # otherwise perform a normal request and cache the response\n retrieved = self._retrieve_data(query_string)\n return self._cache(retrieved, \"item_fields\")"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ncreate new items in Zotero.", "response": "def create_items(self, payload, parentid=None, last_modified=None):\n \"\"\"\n Create new Zotero items\n Accepts two arguments:\n a list containing one or more item dicts\n an optional parent item ID.\n Note that this can also be used to update existing items\n \"\"\"\n if len(payload) > 50:\n raise ze.TooManyItems(\"You may only create up to 50 items per call\")\n # TODO: strip extra data if it's an existing item\n headers = {\"Zotero-Write-Token\": token(), \"Content-Type\": \"application/json\"}\n if last_modified is not None:\n headers[\"If-Unmodified-Since-Version\"] = str(last_modified)\n to_send = json.dumps([i for i in self._cleanup(*payload, allow=(\"key\"))])\n headers.update(self.default_headers())\n req = requests.post(\n url=self.endpoint\n + \"/{t}/{u}/items\".format(t=self.library_type, u=self.library_id),\n data=to_send,\n headers=dict(headers),\n )\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n resp = req.json()\n if parentid:\n # we need to create child items using PATCH\n # TODO: handle possibility of item creation + failed parent\n # attachment\n uheaders = {\n \"If-Unmodified-Since-Version\": req.headers[\"last-modified-version\"]\n }\n uheaders.update(self.default_headers())\n for value in resp[\"success\"].values():\n payload = json.dumps({\"parentItem\": parentid})\n presp = requests.patch(\n url=self.endpoint\n + \"/{t}/{u}/items/{v}\".format(\n t=self.library_type, u=self.library_id, v=value\n ),\n data=payload,\n headers=dict(uheaders),\n )\n self.request = presp\n try:\n presp.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(presp)\n return resp"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef create_collections(self, payload, last_modified=None):\n # no point in proceeding if there's no 'name' key\n for item in payload:\n if \"name\" not in item:\n raise ze.ParamNotPassed(\"The dict you pass must include a 'name' key\")\n # add a blank 'parentCollection' key if it hasn't been passed\n if \"parentCollection\" not in item:\n item[\"parentCollection\"] = \"\"\n headers = {\"Zotero-Write-Token\": token()}\n if last_modified is not None:\n headers[\"If-Unmodified-Since-Version\"] = str(last_modified)\n headers.update(self.default_headers())\n req = requests.post(\n url=self.endpoint\n + \"/{t}/{u}/collections\".format(t=self.library_type, u=self.library_id),\n headers=headers,\n data=json.dumps(payload),\n )\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return req.json()", "response": "Creates a new Zotero collection for the given dict."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nupdate a Zotero collection property such as name collection_id collection_name version and collection_name.", "response": "def update_collection(self, payload, last_modified=None):\n \"\"\"\n Update a Zotero collection property such as 'name'\n Accepts one argument, a dict containing collection data retrieved\n using e.g. 'collections()'\n \"\"\"\n modified = payload[\"version\"]\n if last_modified is not None:\n modified = last_modified\n key = payload[\"key\"]\n headers = {\"If-Unmodified-Since-Version\": str(modified)}\n headers.update(self.default_headers())\n headers.update({\"Content-Type\": \"application/json\"})\n req = requests.put(\n url=self.endpoint\n + \"/{t}/{u}/collections/{c}\".format(\n t=self.library_type, u=self.library_id, c=key\n ),\n headers=headers,\n data=json.dumps(payload),\n )\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef attachment_simple(self, files, parentid=None):\n orig = self._attachment_template(\"imported_file\")\n to_add = [orig.copy() for fls in files]\n for idx, tmplt in enumerate(to_add):\n tmplt[\"title\"] = os.path.basename(files[idx])\n tmplt[\"filename\"] = files[idx]\n if parentid:\n return self._attachment(to_add, parentid)\n else:\n return self._attachment(to_add)", "response": "Add attachments using filenames as title and parentid as parentid"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef attachment_both(self, files, parentid=None):\n orig = self._attachment_template(\"imported_file\")\n to_add = [orig.copy() for f in files]\n for idx, tmplt in enumerate(to_add):\n tmplt[\"title\"] = files[idx][0]\n tmplt[\"filename\"] = files[idx][1]\n if parentid:\n return self._attachment(to_add, parentid)\n else:\n return self._attachment(to_add)", "response": "Add child attachments using title filename"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef update_item(self, payload, last_modified=None):\n to_send = self.check_items([payload])[0]\n if last_modified is None:\n modified = payload[\"version\"]\n else:\n modified = last_modified\n ident = payload[\"key\"]\n headers = {\"If-Unmodified-Since-Version\": str(modified)}\n headers.update(self.default_headers())\n req = requests.patch(\n url=self.endpoint\n + \"/{t}/{u}/items/{id}\".format(\n t=self.library_type, u=self.library_id, id=ident\n ),\n headers=headers,\n data=json.dumps(to_send),\n )\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return True", "response": "Updates an existing item in the library"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef update_items(self, payload):\n to_send = [self.check_items([p])[0] for p in payload]\n headers = {}\n headers.update(self.default_headers())\n # the API only accepts 50 items at a time, so we have to split\n # anything longer\n for chunk in chunks(to_send, 50):\n req = requests.post(\n url=self.endpoint\n + \"/{t}/{u}/items/\".format(t=self.library_type, u=self.library_id),\n headers=headers,\n data=json.dumps(chunk),\n )\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return True", "response": "Updates existing items with new data"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef addto_collection(self, collection, payload):\n ident = payload[\"key\"]\n modified = payload[\"version\"]\n # add the collection data from the item\n modified_collections = payload[\"data\"][\"collections\"] + [collection]\n headers = {\"If-Unmodified-Since-Version\": str(modified)}\n headers.update(self.default_headers())\n req = requests.patch(\n url=self.endpoint\n + \"/{t}/{u}/items/{i}\".format(\n t=self.library_type, u=self.library_id, i=ident\n ),\n data=json.dumps({\"collections\": modified_collections}),\n headers=headers,\n )\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return True", "response": "Adds one or more items to a collection"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef delete_tags(self, *payload):\n if len(payload) > 50:\n raise ze.TooManyItems(\"Only 50 tags or fewer may be deleted\")\n modified_tags = \" || \".join([tag for tag in payload])\n # first, get version data by getting one tag\n self.tags(limit=1)\n headers = {\n \"If-Unmodified-Since-Version\": self.request.headers[\"last-modified-version\"]\n }\n headers.update(self.default_headers())\n req = requests.delete(\n url=self.endpoint\n + \"/{t}/{u}/tags\".format(t=self.library_type, u=self.library_id),\n params={\"tag\": modified_tags},\n headers=headers,\n )\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return True", "response": "Delete a group of tags from the library."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ndeleting Items from a Zotero library", "response": "def delete_item(self, payload, last_modified=None):\n \"\"\"\n Delete Items from a Zotero library\n Accepts a single argument:\n a dict containing item data\n OR a list of dicts containing item data\n \"\"\"\n params = None\n if isinstance(payload, list):\n params = {\"itemKey\": \",\".join([p[\"key\"] for p in payload])}\n if last_modified is not None:\n modified = last_modified\n else:\n modified = payload[0][\"version\"]\n url = self.endpoint + \"/{t}/{u}/items\".format(\n t=self.library_type, u=self.library_id\n )\n else:\n ident = payload[\"key\"]\n if last_modified is not None:\n modified = last_modified\n else:\n modified = payload[\"version\"]\n url = self.endpoint + \"/{t}/{u}/items/{c}\".format(\n t=self.library_type, u=self.library_id, c=ident\n )\n headers = {\"If-Unmodified-Since-Version\": str(modified)}\n headers.update(self.default_headers())\n req = requests.delete(url=url, params=params, headers=headers)\n self.request = req\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n return True"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _validate(self, conditions):\n allowed_keys = set(self.searchkeys)\n operators_set = set(self.operators.keys())\n for condition in conditions:\n if set(condition.keys()) != allowed_keys:\n raise ze.ParamNotPassed(\n \"Keys must be all of: %s\" % \", \".join(self.searchkeys)\n )\n if condition.get(\"operator\") not in operators_set:\n raise ze.ParamNotPassed(\n \"You have specified an unknown operator: %s\"\n % condition.get(\"operator\")\n )\n # dict keys of allowed operators for the current condition\n permitted_operators = self.conditions_operators.get(\n condition.get(\"condition\")\n )\n # transform these into values\n permitted_operators_list = set(\n [self.operators.get(op) for op in permitted_operators]\n )\n if condition.get(\"operator\") not in permitted_operators_list:\n raise ze.ParamNotPassed(\n \"You may not use the '%s' operator when selecting the '%s' condition. \\nAllowed operators: %s\"\n % (\n condition.get(\"operator\"),\n condition.get(\"condition\"),\n \", \".join(list(permitted_operators_list)),\n )\n )", "response": "Validate saved search conditions raising an error if any contain invalid operators"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nverify that the file at the current location is a file and that all files to be attached exist and that the file at the current location is a file.", "response": "def _verify(self, payload):\n \"\"\"\n ensure that all files to be attached exist\n open()'s better than exists(), cos it avoids a race condition\n \"\"\"\n if not payload: # Check payload has nonzero length\n raise ze.ParamNotPassed\n for templt in payload:\n if os.path.isfile(str(self.basedir.joinpath(templt[\"filename\"]))):\n try:\n # if it is a file, try to open it, and catch the error\n with open(str(self.basedir.joinpath(templt[\"filename\"]))):\n pass\n except IOError:\n raise ze.FileDoesNotExist(\n \"The file at %s couldn't be opened or found.\"\n % str(self.basedir.joinpath(templt[\"filename\"]))\n )\n # no point in continuing if the file isn't a file\n else:\n raise ze.FileDoesNotExist(\n \"The file at %s couldn't be opened or found.\"\n % str(self.basedir.joinpath(templt[\"filename\"]))\n )"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _create_prelim(self):\n self._verify(self.payload)\n if \"key\" in self.payload[0] and self.payload[0][\"key\"]:\n if next((i for i in self.payload if \"key\" not in i), False):\n raise ze.UnsupportedParams(\n \"Can't pass payload entries with and without keys to Zupload\"\n )\n return None # Don't do anything if payload comes with keys\n liblevel = \"/{t}/{u}/items\"\n # Create one or more new attachments\n headers = {\"Zotero-Write-Token\": token(), \"Content-Type\": \"application/json\"}\n headers.update(self.zinstance.default_headers())\n # If we have a Parent ID, add it as a parentItem\n if self.parentid:\n for child in self.payload:\n child[\"parentItem\"] = self.parentid\n to_send = json.dumps(self.payload)\n req = requests.post(\n url=self.zinstance.endpoint\n + liblevel.format(\n t=self.zinstance.library_type, u=self.zinstance.library_id\n ),\n data=to_send,\n headers=headers,\n )\n try:\n req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(req)\n data = req.json()\n for k in data[\"success\"]:\n self.payload[int(k)][\"key\"] = data[\"success\"][k]\n return data", "response": "Create one or more new attachments for the current object"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nstep 1 : get upload authorisation for a file", "response": "def _get_auth(self, attachment, reg_key, md5=None):\n \"\"\"\n Step 1: get upload authorisation for a file\n \"\"\"\n mtypes = mimetypes.guess_type(attachment)\n digest = hashlib.md5()\n with open(attachment, \"rb\") as att:\n for chunk in iter(lambda: att.read(8192), b\"\"):\n digest.update(chunk)\n auth_headers = {\"Content-Type\": \"application/x-www-form-urlencoded\"}\n if not md5:\n auth_headers[\"If-None-Match\"] = \"*\"\n else:\n # docs specify that for existing file we use this\n auth_headers[\"If-Match\"] = md5\n auth_headers.update(self.zinstance.default_headers())\n data = {\n \"md5\": digest.hexdigest(),\n \"filename\": os.path.basename(attachment),\n \"filesize\": os.path.getsize(attachment),\n \"mtime\": str(int(os.path.getmtime(attachment) * 1000)),\n \"contentType\": mtypes[0] or \"application/octet-stream\",\n \"charset\": mtypes[1],\n \"params\": 1,\n }\n auth_req = requests.post(\n url=self.zinstance.endpoint\n + \"/{t}/{u}/items/{i}/file\".format(\n t=self.zinstance.library_type, u=self.zinstance.library_id, i=reg_key\n ),\n data=data,\n headers=auth_headers,\n )\n try:\n auth_req.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(auth_req)\n return auth_req.json()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nstep 1 Upload file to server and return a new entry in the cache", "response": "def _upload_file(self, authdata, attachment, reg_key):\n \"\"\"\n Step 2: auth successful, and file not on server\n zotero.org/support/dev/server_api/file_upload#a_full_upload\n\n reg_key isn't used, but we need to pass it through to Step 3\n \"\"\"\n upload_dict = authdata[\n \"params\"\n ] # using params now since prefix/suffix concat was giving ConnectionError\n # must pass tuple of tuples not dict to ensure key comes first\n upload_list = [(\"key\", upload_dict[\"key\"])]\n for k in upload_dict:\n if k != \"key\":\n upload_list.append((k, upload_dict[k]))\n # The prior code for attaching file gave me content not match md5\n # errors\n upload_list.append((\"file\", open(attachment, \"rb\").read()))\n upload_pairs = tuple(upload_list)\n try:\n upload = requests.post(\n url=authdata[\"url\"],\n files=upload_pairs,\n headers={\n # \"Content-Type\": authdata['contentType'],\n \"User-Agent\": \"Pyzotero/%s\"\n % __version__\n },\n )\n except (requests.exceptions.ConnectionError):\n raise ze.UploadError(\"ConnectionError\")\n try:\n upload.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(upload)\n # now check the responses\n return self._register_upload(authdata, reg_key)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nsteps 3 : upload successful so register it", "response": "def _register_upload(self, authdata, reg_key):\n \"\"\"\n Step 3: upload successful, so register it\n \"\"\"\n reg_headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"If-None-Match\": \"*\",\n }\n reg_headers.update(self.zinstance.default_headers())\n reg_data = {\"upload\": authdata.get(\"uploadKey\")}\n upload_reg = requests.post(\n url=self.zinstance.endpoint\n + \"/{t}/{u}/items/{i}/file\".format(\n t=self.zinstance.library_type, u=self.zinstance.library_id, i=reg_key\n ),\n data=reg_data,\n headers=dict(reg_headers),\n )\n try:\n upload_reg.raise_for_status()\n except requests.exceptions.HTTPError:\n error_handler(upload_reg)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nfiling upload functionality Goes through upload steps 0 - 3 (private class methods), and returns a dict noting success, failure, or unchanged (returning the payload entries with that property as a list for each status)", "response": "def upload(self):\n \"\"\"\n File upload functionality\n\n Goes through upload steps 0 - 3 (private class methods), and returns\n a dict noting success, failure, or unchanged\n (returning the payload entries with that property as a list for each status)\n \"\"\"\n result = {\"success\": [], \"failure\": [], \"unchanged\": []}\n self._create_prelim()\n for item in self.payload:\n if \"key\" not in item:\n result[\"failure\"].append(item)\n continue\n attach = str(self.basedir.joinpath(item[\"filename\"]))\n authdata = self._get_auth(attach, item[\"key\"], md5=item.get(\"md5\", None))\n # no need to keep going if the file exists\n if authdata.get(\"exists\"):\n result[\"unchanged\"].append(item)\n continue\n self._upload_file(authdata, attach, item[\"key\"])\n result[\"success\"].append(item)\n return result"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nidentifying the location of an executable file.", "response": "def which(program, win_allow_cross_arch=True):\n \"\"\"Identify the location of an executable file.\"\"\"\n def is_exe(path):\n return os.path.isfile(path) and os.access(path, os.X_OK)\n\n def _get_path_list():\n return os.environ['PATH'].split(os.pathsep)\n\n if os.name == 'nt':\n def find_exe(program):\n root, ext = os.path.splitext(program)\n if ext:\n if is_exe(program):\n return program\n else:\n for ext in os.environ['PATHEXT'].split(os.pathsep):\n program_path = root + ext.lower()\n if is_exe(program_path):\n return program_path\n return None\n\n def get_path_list():\n paths = _get_path_list()\n if win_allow_cross_arch:\n alt_sys_path = os.path.expandvars(r\"$WINDIR\\Sysnative\")\n if os.path.isdir(alt_sys_path):\n paths.insert(0, alt_sys_path)\n else:\n alt_sys_path = os.path.expandvars(r\"$WINDIR\\SysWOW64\")\n if os.path.isdir(alt_sys_path):\n paths.append(alt_sys_path)\n return paths\n\n else:\n def find_exe(program):\n return program if is_exe(program) else None\n\n get_path_list = _get_path_list\n\n if os.path.split(program)[0]:\n program_path = find_exe(program)\n if program_path:\n return program_path\n else:\n for path in get_path_list():\n program_path = find_exe(os.path.join(path, program))\n if program_path:\n return program_path\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nsplit a multiline string into a list excluding blank lines.", "response": "def split_multiline(value):\n \"\"\"Split a multiline string into a list, excluding blank lines.\"\"\"\n return [element for element in (line.strip() for line in value.split('\\n'))\n if element]"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nsplits a string with comma or space - separated elements into a list.", "response": "def split_elements(value):\n \"\"\"Split a string with comma or space-separated elements into a list.\"\"\"\n items = [v.strip() for v in value.split(',')]\n if len(items) == 1:\n items = value.split()\n return items"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef cfg_to_args(config):\n kwargs = {}\n opts_to_args = {\n 'metadata': [\n ('name', 'name'),\n ('author', 'author'),\n ('author-email', 'author_email'),\n ('maintainer', 'maintainer'),\n ('maintainer-email', 'maintainer_email'),\n ('home-page', 'url'),\n ('summary', 'description'),\n ('description', 'long_description'),\n ('download-url', 'download_url'),\n ('classifier', 'classifiers'),\n ('platform', 'platforms'),\n ('license', 'license'),\n ('keywords', 'keywords'),\n ],\n 'files': [\n ('packages_root', 'package_dir'),\n ('packages', 'packages'),\n ('modules', 'py_modules'),\n ('scripts', 'scripts'),\n ('package_data', 'package_data'),\n ('data_files', 'data_files'),\n ],\n }\n\n opts_to_args['metadata'].append(('requires-dist', 'install_requires'))\n if IS_PY2K and not which('3to2'):\n kwargs['setup_requires'] = ['3to2']\n kwargs['zip_safe'] = False\n\n for section in opts_to_args:\n for option, argname in opts_to_args[section]:\n value = get_cfg_value(config, section, option)\n if value:\n kwargs[argname] = value\n\n if 'long_description' not in kwargs:\n kwargs['long_description'] = read_description_file(config)\n\n if 'package_dir' in kwargs:\n kwargs['package_dir'] = {'': kwargs['package_dir']}\n\n if 'keywords' in kwargs:\n kwargs['keywords'] = split_elements(kwargs['keywords'])\n\n if 'package_data' in kwargs:\n kwargs['package_data'] = get_package_data(kwargs['package_data'])\n\n if 'data_files' in kwargs:\n kwargs['data_files'] = get_data_files(kwargs['data_files'])\n\n kwargs['version'] = get_version()\n\n if not IS_PY2K:\n kwargs['test_suite'] = 'test'\n\n return kwargs", "response": "Compatibility helper to use setup. cfg in setup. py."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef run_3to2(args=None):\n args = BASE_ARGS_3TO2 if args is None else BASE_ARGS_3TO2 + args\n try:\n proc = subprocess.Popen(['3to2'] + args, stderr=subprocess.PIPE)\n except OSError:\n for path in glob.glob('*.egg'):\n if os.path.isdir(path) and path not in sys.path:\n sys.path.append(path)\n try:\n from lib3to2.main import main as lib3to2_main\n except ImportError:\n raise OSError('3to2 script is unavailable.')\n else:\n if lib3to2_main('lib3to2.fixes', args):\n raise Exception('lib3to2 parsing error')\n else:\n # HACK: workaround for 3to2 never returning non-zero\n # when using the -j option.\n num_errors = 0\n while proc.poll() is None:\n line = proc.stderr.readline()\n sys.stderr.write(line)\n num_errors += line.count(': ParseError: ')\n if proc.returncode or num_errors:\n raise Exception('lib3to2 parsing error')", "response": "Convert Python files using lib3to2."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nwrite Python 2 shebang and add encoding cookie if needed.", "response": "def write_py2k_header(file_list):\n \"\"\"Write Python 2 shebang and add encoding cookie if needed.\"\"\"\n if not isinstance(file_list, list):\n file_list = [file_list]\n\n python_re = re.compile(br\"^(#!.*\\bpython)(.*)([\\r\\n]+)$\")\n coding_re = re.compile(br\"coding[:=]\\s*([-\\w.]+)\")\n new_line_re = re.compile(br\"([\\r\\n]+)$\")\n version_3 = LooseVersion('3')\n\n for file in file_list:\n if not os.path.getsize(file):\n continue\n\n rewrite_needed = False\n python_found = False\n coding_found = False\n lines = []\n\n f = open(file, 'rb')\n try:\n while len(lines) < 2:\n line = f.readline()\n match = python_re.match(line)\n if match:\n python_found = True\n version = LooseVersion(match.group(2).decode() or '2')\n try:\n version_test = version >= version_3\n except TypeError:\n version_test = True\n if version_test:\n line = python_re.sub(br\"\\g<1>2\\g<3>\", line)\n rewrite_needed = True\n elif coding_re.search(line):\n coding_found = True\n lines.append(line)\n if not coding_found:\n match = new_line_re.search(lines[0])\n newline = match.group(1) if match else b\"\\n\"\n line = b\"# -*- coding: utf-8 -*-\" + newline\n lines.insert(1 if python_found else 0, line)\n rewrite_needed = True\n if rewrite_needed:\n lines += f.readlines()\n finally:\n f.close()\n\n if rewrite_needed:\n f = open(file, 'wb')\n try:\n f.writelines(lines)\n finally:\n f.close()"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef which(program):\n if os.path.split(program)[0]:\n program_path = find_exe(program)\n if program_path:\n return program_path\n else:\n for path in get_path_list():\n program_path = find_exe(os.path.join(path, program))\n if program_path:\n return program_path\n return None", "response": "Identify the location of an executable file."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets the set of languages supported by the language tool.", "response": "def get_languages() -> set:\n \"\"\"Get supported languages.\"\"\"\n try:\n languages = cache['languages']\n except KeyError:\n languages = LanguageTool._get_languages()\n cache['languages'] = languages\n return languages"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nmatches text against enabled rules.", "response": "def check(self, text: str, srctext=None) -> [Match]:\n \"\"\"Match text against enabled rules.\"\"\"\n root = self._get_root(self._url, self._encode(text, srctext))\n return [Match(e.attrib) for e in root if e.tag == 'error']"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nmatch text against enabled rules ( result in XML format.", "response": "def _check_api(self, text: str, srctext=None) -> bytes:\n \"\"\"Match text against enabled rules (result in XML format).\"\"\"\n root = self._get_root(self._url, self._encode(text, srctext))\n return (b'\\n' +\n ElementTree.tostring(root) + b\"\\n\")"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef correct(self, text: str, srctext=None) -> str:\n return correct(text, self.check(text, srctext))", "response": "Automatically apply suggestions to the text."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef parse_java_version(version_text):\n match = re.search(JAVA_VERSION_REGEX, version_text)\n if not match:\n raise SystemExit(\n 'Could not parse Java version from \"\"\"{}\"\"\".'.format(version_text))\n\n return (int(match.group('major1')), int(match.group('major2')))", "response": "Parse Java version from version_text."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn newest compatible version.", "response": "def get_newest_possible_languagetool_version():\n \"\"\"Return newest compatible version.\n\n >>> version = get_newest_possible_languagetool_version()\n >>> version in [JAVA_6_COMPATIBLE_VERSION,\n ... JAVA_7_COMPATIBLE_VERSION,\n ... LATEST_VERSION]\n True\n\n \"\"\"\n java_path = find_executable('java')\n if not java_path:\n # Just ignore this and assume an old version of Java. It might not be\n # found because of a PATHEXT-related issue\n # (https://bugs.python.org/issue2200).\n return JAVA_6_COMPATIBLE_VERSION\n\n output = subprocess.check_output([java_path, '-version'],\n stderr=subprocess.STDOUT,\n universal_newlines=True)\n\n java_version = parse_java_version(output)\n\n if java_version >= (1, 8):\n return LATEST_VERSION\n elif java_version >= (1, 7):\n return JAVA_7_COMPATIBLE_VERSION\n elif java_version >= (1, 6):\n warn('language-check would be able to use a newer version of '\n 'LanguageTool if you had Java 7 or newer installed')\n return JAVA_6_COMPATIBLE_VERSION\n else:\n raise SystemExit(\n 'You need at least Java 6 to use language-check')"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_common_prefix(z):\n name_list = z.namelist()\n if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]):\n return name_list[0]\n return None", "response": "Get common prefix in a zip file if any."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _process_events(self, events):\n for f, callback, transferred, key, ov in events:\n try:\n self._logger.debug('Invoking event callback {}'.format(callback))\n value = callback(transferred, key, ov)\n except OSError:\n self._logger.warning('Event callback failed', exc_info=sys.exc_info())\n else:\n f.set_result(value)", "response": "Process events from proactor."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef asyncClose(fn):\n @functools.wraps(fn)\n def wrapper(*args, **kwargs):\n f = asyncio.ensure_future(fn(*args, **kwargs))\n while not f.done():\n QApplication.instance().processEvents()\n\n return wrapper", "response": "Decorator that allows to run async code before application is closed."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef asyncSlot(*args):\n def outer_decorator(fn):\n @Slot(*args)\n @functools.wraps(fn)\n def wrapper(*args, **kwargs):\n asyncio.ensure_future(fn(*args, **kwargs))\n return wrapper\n return outer_decorator", "response": "Make a Qt async slot run on asyncio loop."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nclassing decorator to add a logger to a class.", "response": "def with_logger(cls):\n \"\"\"Class decorator to add a logger to a class.\"\"\"\n attr_name = '_logger'\n cls_name = cls.__qualname__\n module = cls.__module__\n if module is not None:\n cls_name = module + '.' + cls_name\n else:\n raise AssertionError\n setattr(cls, attr_name, logging.getLogger(cls_name))\n return cls"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef addSources(self, *sources):\n self._sources.extend(sources)\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'current MIB source(s): %s' % ', '.join([str(x) for x in self._sources]))\n\n return self", "response": "Add more ASN. 1 MIB source repositories."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nadd more transformed MIBs repositories.", "response": "def addSearchers(self, *searchers):\n \"\"\"Add more transformed MIBs repositories.\n\n MibCompiler.compile will invoke each of configured searcher objects\n in order of their addition asking each if already transformed MIB\n module already exists and is more recent than specified.\n\n Args:\n searchers: searcher object(s)\n\n Returns:\n reference to itself (can be used for call chaining)\n\n \"\"\"\n self._searchers.extend(searchers)\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'current compiled MIBs location(s): %s' % ', '.join([str(x) for x in self._searchers]))\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nadd more transformed MIBs to borrow MIBs from.", "response": "def addBorrowers(self, *borrowers):\n \"\"\"Add more transformed MIBs repositories to borrow MIBs from.\n\n Whenever MibCompiler.compile encounters MIB module which neither of\n the *searchers* can find or fetched ASN.1 MIB module can not be\n parsed (due to syntax errors), these *borrowers* objects will be\n invoked in order of their addition asking each if already transformed\n MIB can be fetched (borrowed).\n\n Args:\n borrowers: borrower object(s)\n\n Returns:\n reference to itself (can be used for call chaining)\n\n \"\"\"\n self._borrowers.extend(borrowers)\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'current MIB borrower(s): %s' % ', '.join([str(x) for x in self._borrowers]))\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncompile the MIBs in the specified list of MIBs and return a dictionary of MIBs and status information.", "response": "def compile(self, *mibnames, **options):\n \"\"\"Transform requested and possibly referred MIBs.\n\n The *compile* method should be invoked when *MibCompiler* object\n is operational meaning at least *sources* are specified.\n\n Once called with a MIB module name, *compile* will:\n\n * fetch ASN.1 MIB module with given name by calling *sources*\n * make sure no such transformed MIB already exists (with *searchers*)\n * parse ASN.1 MIB text with *parser*\n * perform actual MIB transformation into target format with *code generator*\n * may attempt to borrow pre-transformed MIB through *borrowers*\n * write transformed MIB through *writer*\n\n The above sequence will be performed for each MIB name given in\n *mibnames* and may be performed for all MIBs referred to from\n MIBs being processed.\n\n Args:\n mibnames: list of ASN.1 MIBs names\n options: options that affect the way PySMI components work\n\n Returns:\n A dictionary of MIB module names processed (keys) and *MibStatus*\n class instances (values)\n\n \"\"\"\n processed = {}\n parsedMibs = {}\n failedMibs = {}\n borrowedMibs = {}\n builtMibs = {}\n symbolTableMap = {}\n mibsToParse = [x for x in mibnames]\n canonicalMibNames = {}\n\n while mibsToParse:\n mibname = mibsToParse.pop(0)\n\n if mibname in parsedMibs:\n debug.logger & debug.flagCompiler and debug.logger('MIB %s already parsed' % mibname)\n continue\n\n if mibname in failedMibs:\n debug.logger & debug.flagCompiler and debug.logger('MIB %s already failed' % mibname)\n continue\n\n for source in self._sources:\n debug.logger & debug.flagCompiler and debug.logger('trying source %s' % source)\n\n try:\n fileInfo, fileData = source.getData(mibname)\n\n for mibTree in self._parser.parse(fileData):\n mibInfo, symbolTable = self._symbolgen.genCode(\n mibTree, symbolTableMap\n )\n\n symbolTableMap[mibInfo.name] = symbolTable\n\n parsedMibs[mibInfo.name] = fileInfo, mibInfo, mibTree\n\n if mibname in failedMibs:\n del failedMibs[mibname]\n\n mibsToParse.extend(mibInfo.imported)\n\n if fileInfo.name in mibnames:\n if mibInfo.name not in canonicalMibNames:\n canonicalMibNames[mibInfo.name] = []\n canonicalMibNames[mibInfo.name].append(fileInfo.name)\n\n debug.logger & debug.flagCompiler and debug.logger(\n '%s (%s) read from %s, immediate dependencies: %s' % (\n mibInfo.name, mibname, fileInfo.path, ', '.join(mibInfo.imported) or ''))\n\n break\n\n except error.PySmiReaderFileNotFoundError:\n debug.logger & debug.flagCompiler and debug.logger('no %s found at %s' % (mibname, source))\n continue\n\n except error.PySmiError:\n exc_class, exc, tb = sys.exc_info()\n exc.source = source\n exc.mibname = mibname\n exc.msg += ' at MIB %s' % mibname\n\n debug.logger & debug.flagCompiler and debug.logger('%serror %s from %s' % (\n options.get('ignoreErrors') and 'ignoring ' or 'failing on ', exc, source))\n\n failedMibs[mibname] = exc\n\n processed[mibname] = statusFailed.setOptions(error=exc)\n\n else:\n exc = error.PySmiError('MIB source %s not found' % mibname)\n exc.mibname = mibname\n debug.logger & debug.flagCompiler and debug.logger('no %s found everywhere' % mibname)\n\n if mibname not in failedMibs:\n failedMibs[mibname] = exc\n\n if mibname not in processed:\n processed[mibname] = statusMissing\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'MIBs analyzed %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs)))\n\n #\n # See what MIBs need generating\n #\n\n for mibname in tuple(parsedMibs):\n fileInfo, mibInfo, mibTree = parsedMibs[mibname]\n\n debug.logger & debug.flagCompiler and debug.logger('checking if %s requires updating' % mibname)\n\n for searcher in self._searchers:\n try:\n searcher.fileExists(mibname, fileInfo.mtime, rebuild=options.get('rebuild'))\n\n except error.PySmiFileNotFoundError:\n debug.logger & debug.flagCompiler and debug.logger(\n 'no compiled MIB %s available through %s' % (mibname, searcher))\n continue\n\n except error.PySmiFileNotModifiedError:\n debug.logger & debug.flagCompiler and debug.logger(\n 'will be using existing compiled MIB %s found by %s' % (mibname, searcher))\n del parsedMibs[mibname]\n processed[mibname] = statusUntouched\n break\n\n except error.PySmiError:\n exc_class, exc, tb = sys.exc_info()\n exc.searcher = searcher\n exc.mibname = mibname\n exc.msg += ' at MIB %s' % mibname\n debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (searcher, exc))\n continue\n\n else:\n debug.logger & debug.flagCompiler and debug.logger(\n 'no suitable compiled MIB %s found anywhere' % mibname)\n\n if options.get('noDeps') and mibname not in canonicalMibNames:\n debug.logger & debug.flagCompiler and debug.logger(\n 'excluding imported MIB %s from code generation' % mibname)\n del parsedMibs[mibname]\n processed[mibname] = statusUntouched\n continue\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'MIBs parsed %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs)))\n\n #\n # Generate code for parsed MIBs\n #\n\n for mibname in parsedMibs.copy():\n fileInfo, mibInfo, mibTree = parsedMibs[mibname]\n\n debug.logger & debug.flagCompiler and debug.logger('compiling %s read from %s' % (mibname, fileInfo.path))\n\n platform_info, user_info = self._get_system_info()\n\n comments = [\n 'ASN.1 source %s' % fileInfo.path,\n 'Produced by %s-%s at %s' % (packageName, packageVersion, time.asctime()),\n 'On host %s platform %s version %s by user %s' % (platform_info[1], platform_info[0],\n platform_info[2], user_info[0]),\n 'Using Python version %s' % sys.version.split('\\n')[0]\n ]\n\n try:\n mibInfo, mibData = self._codegen.genCode(\n mibTree,\n symbolTableMap,\n comments=comments,\n dstTemplate=options.get('dstTemplate'),\n genTexts=options.get('genTexts'),\n textFilter=options.get('textFilter')\n )\n\n builtMibs[mibname] = fileInfo, mibInfo, mibData\n del parsedMibs[mibname]\n\n debug.logger & debug.flagCompiler and debug.logger(\n '%s read from %s and compiled by %s' % (mibname, fileInfo.path, self._writer))\n\n except error.PySmiError:\n exc_class, exc, tb = sys.exc_info()\n exc.handler = self._codegen\n exc.mibname = mibname\n exc.msg += ' at MIB %s' % mibname\n\n debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (self._codegen, exc))\n\n processed[mibname] = statusFailed.setOptions(error=exc)\n\n failedMibs[mibname] = exc\n del parsedMibs[mibname]\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'MIBs built %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs)))\n\n #\n # Try to borrow pre-compiled MIBs for failed ones\n #\n\n for mibname in failedMibs.copy():\n if options.get('noDeps') and mibname not in canonicalMibNames:\n debug.logger & debug.flagCompiler and debug.logger('excluding imported MIB %s from borrowing' % mibname)\n continue\n\n for borrower in self._borrowers:\n debug.logger & debug.flagCompiler and debug.logger('trying to borrow %s from %s' % (mibname, borrower))\n try:\n fileInfo, fileData = borrower.getData(\n mibname,\n genTexts=options.get('genTexts')\n )\n\n borrowedMibs[mibname] = fileInfo, MibInfo(name=mibname, imported=[]), fileData\n\n del failedMibs[mibname]\n\n debug.logger & debug.flagCompiler and debug.logger('%s borrowed with %s' % (mibname, borrower))\n break\n\n except error.PySmiError:\n debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (borrower, sys.exc_info()[1]))\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'MIBs available for borrowing %s, MIBs failed %s' % (len(borrowedMibs), len(failedMibs)))\n\n #\n # See what MIBs need borrowing\n #\n\n for mibname in borrowedMibs.copy():\n debug.logger & debug.flagCompiler and debug.logger('checking if failed MIB %s requires borrowing' % mibname)\n\n fileInfo, mibInfo, mibData = borrowedMibs[mibname]\n\n for searcher in self._searchers:\n try:\n searcher.fileExists(mibname, fileInfo.mtime, rebuild=options.get('rebuild'))\n\n except error.PySmiFileNotFoundError:\n debug.logger & debug.flagCompiler and debug.logger(\n 'no compiled MIB %s available through %s' % (mibname, searcher))\n continue\n\n except error.PySmiFileNotModifiedError:\n debug.logger & debug.flagCompiler and debug.logger(\n 'will be using existing compiled MIB %s found by %s' % (mibname, searcher))\n del borrowedMibs[mibname]\n processed[mibname] = statusUntouched\n break\n\n except error.PySmiError:\n exc_class, exc, tb = sys.exc_info()\n exc.searcher = searcher\n exc.mibname = mibname\n exc.msg += ' at MIB %s' % mibname\n\n debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (searcher, exc))\n\n continue\n else:\n debug.logger & debug.flagCompiler and debug.logger(\n 'no suitable compiled MIB %s found anywhere' % mibname)\n\n if options.get('noDeps') and mibname not in canonicalMibNames:\n debug.logger & debug.flagCompiler and debug.logger(\n 'excluding imported MIB %s from borrowing' % mibname)\n processed[mibname] = statusUntouched\n\n else:\n debug.logger & debug.flagCompiler and debug.logger('will borrow MIB %s' % mibname)\n builtMibs[mibname] = borrowedMibs[mibname]\n\n processed[mibname] = statusBorrowed.setOptions(\n path=fileInfo.path, file=fileInfo.file,\n alias=fileInfo.name\n )\n\n del borrowedMibs[mibname]\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'MIBs built %s, MIBs failed %s' % (len(builtMibs), len(failedMibs)))\n\n #\n # We could attempt to ignore missing/failed MIBs\n #\n\n if failedMibs and not options.get('ignoreErrors'):\n debug.logger & debug.flagCompiler and debug.logger('failing with problem MIBs %s' % ', '.join(failedMibs))\n\n for mibname in builtMibs:\n processed[mibname] = statusUnprocessed\n\n return processed\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'proceeding with built MIBs %s, failed MIBs %s' % (', '.join(builtMibs), ', '.join(failedMibs)))\n\n #\n # Store compiled MIBs\n #\n\n for mibname in builtMibs.copy():\n fileInfo, mibInfo, mibData = builtMibs[mibname]\n\n try:\n if options.get('writeMibs', True):\n self._writer.putData(\n mibname, mibData, dryRun=options.get('dryRun')\n )\n\n debug.logger & debug.flagCompiler and debug.logger('%s stored by %s' % (mibname, self._writer))\n\n del builtMibs[mibname]\n\n if mibname not in processed:\n processed[mibname] = statusCompiled.setOptions(\n path=fileInfo.path,\n file=fileInfo.file,\n alias=fileInfo.name,\n oid=mibInfo.oid,\n oids=mibInfo.oids,\n identity=mibInfo.identity,\n revision=mibInfo.revision,\n enterprise=mibInfo.enterprise,\n compliance=mibInfo.compliance,\n )\n\n except error.PySmiError:\n exc_class, exc, tb = sys.exc_info()\n exc.handler = self._codegen\n exc.mibname = mibname\n exc.msg += ' at MIB %s' % mibname\n\n debug.logger & debug.flagCompiler and debug.logger('error %s from %s' % (exc, self._writer))\n\n processed[mibname] = statusFailed.setOptions(error=exc)\n failedMibs[mibname] = exc\n del builtMibs[mibname]\n\n debug.logger & debug.flagCompiler and debug.logger(\n 'MIBs modified: %s' % ', '.join([x for x in processed if processed[x] in ('compiled', 'borrowed')]))\n\n return processed"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef p_modules(self, p):\n n = len(p)\n if n == 3:\n p[0] = p[1] + [p[2]]\n elif n == 2:\n p[0] = [p[1]]", "response": "A function to add the modules to the list of modules."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nparses the importPart of a module", "response": "def p_importPart(self, p):\n \"\"\"importPart : imports\n | empty\"\"\"\n # libsmi: TODO: ``IMPORTS ;'' allowed? refer ASN.1!\n if p[1]:\n importDict = {}\n for imp in p[1]: # don't do just dict() because moduleNames may be repeated\n fromModule, symbols = imp\n if fromModule in importDict:\n importDict[fromModule] += symbols\n else:\n importDict[fromModule] = symbols\n\n p[0] = importDict"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef p_imports(self, p):\n n = len(p)\n if n == 3:\n p[0] = p[1] + [p[2]]\n elif n == 2:\n p[0] = [p[1]]", "response": "imports : imports import\n | import"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef p_importIdentifiers(self, p):\n n = len(p)\n if n == 4:\n p[0] = p[1] + [p[3]]\n elif n == 2:\n p[0] = [p[1]]", "response": "A function to add importIdentifiers to a list of parameters."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef p_typeDeclarationRHS(self, p):\n if p[1]:\n if p[1] == 'TEXTUAL-CONVENTION':\n p[0] = ('typeDeclarationRHS', p[2], # display\n p[4], # status\n (p[5], p[6]), # description\n p[7], # reference\n p[9]) # syntax\n else:\n p[0] = ('typeDeclarationRHS', p[1])", "response": "p_typeDeclarationRHS - Adds typeDeclarationRHS to the parser p."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nparsing the sequence items list", "response": "def p_sequenceItems(self, p):\n \"\"\"sequenceItems : sequenceItems ',' sequenceItem\n | sequenceItem\"\"\"\n # libsmi: TODO: might this list be emtpy?\n n = len(p)\n if n == 4:\n p[0] = p[1] + [p[3]]\n elif n == 2:\n p[0] = [p[1]]"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef p_objectIdentityClause(self, p):\n p[0] = ('objectIdentityClause', p[1], # id\n # p[2], # OBJECT_IDENTITY\n p[4], # status\n (p[5], p[6]), # description\n p[7], # reference\n p[10])", "response": "P objectIdentityClause - objectIdentityClause"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef p_objectTypeClause(self, p):\n p[0] = ('objectTypeClause', p[1], # id\n # p[2], # OBJECT_TYPE\n p[4], # syntax\n p[5], # UnitsPart\n p[6], # MaxOrPIBAccessPart\n p[8], # status\n p[9], # descriptionClause\n p[10], # reference\n p[11], # augmentions\n p[12], # index\n p[13], # DefValPart\n p[16])", "response": "P objectTypeClause - Puts the objectTypeClause into the pattern p"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef p_moduleIdentityClause(self, p):\n p[0] = ('moduleIdentityClause', p[1], # id\n # p[2], # MODULE_IDENTITY\n # XXX p[3], # SubjectCategoriesPart\n (p[4], p[5]), # last updated\n (p[6], p[7]), # organization\n (p[8], p[9]), # contact info\n (p[10], p[11]), # description\n p[12], # RevisionPart\n p[15])", "response": "P_moduleIdentityClause - > moduleIdentityClause"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef p_valueofSimpleSyntax(self, p):\n # libsmi for objectIdentifier_defval:\n # This is only for some MIBs with invalid numerical\n # OID notation for DEFVALs. We DO NOT parse them\n # correctly. We just don't want to produce a\n # parser error.\n n = len(p)\n if n == 2:\n p[0] = p[1]\n elif n == 4: # XXX\n pass", "response": "Parse the valueofSimpleSyntax parameter."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef p_sequenceSimpleSyntax(self, p):\n n = len(p)\n if n == 3:\n p[0] = p[1] # XXX not supporting subtypes here\n elif n == 4:\n p[0] = p[1] + ' ' + p[2]", "response": "parse the sequenceSimpleSyntax element"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef p_ApplicationSyntax(self, p):\n # COUNTER32 and COUNTER64 was with anySubType in libsmi\n n = len(p)\n if n == 2:\n p[0] = ('ApplicationSyntax', p[1])\n elif n == 3:\n p[0] = ('ApplicationSyntax', p[1], p[2])", "response": "P_ApplicationSyntax - Set application syntax."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nparses the sequence application syntax", "response": "def p_sequenceApplicationSyntax(self, p):\n \"\"\"sequenceApplicationSyntax : IPADDRESS anySubType\n | COUNTER32 anySubType\n | GAUGE32 anySubType\n | UNSIGNED32 anySubType\n | TIMETICKS anySubType\n | OPAQUE\n | COUNTER64 anySubType\"\"\"\n n = len(p)\n if n == 2:\n p[0] = p[1]\n elif n == 3:\n p[0] = p[1]"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nrange | range | range", "response": "def p_ranges(self, p):\n \"\"\"ranges : ranges '|' range\n | range\"\"\"\n n = len(p)\n if n == 4:\n p[0] = p[1] + [p[3]]\n elif n == 2:\n p[0] = [p[1]]"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef p_range(self, p):\n n = len(p)\n if n == 2:\n p[0] = (p[1],)\n elif n == 4:\n p[0] = (p[1], p[3])", "response": "range : value DOT_DOT value\n | value"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef p_IndexType(self, p):\n n = len(p)\n if n == 2:\n p[0] = (0, p[1])\n elif n == 3:\n p[0] = (1, p[2])", "response": "IndexType IMPLIED Index\n | Index"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef p_Value(self, p):\n n = len(p)\n if n == 2:\n p[0] = p[1]\n elif n == 4:\n p[0] = p[2]", "response": "Value : valueofObjectSyntax\n | '{' BitsValue '}"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef p_BitNames(self, p):\n n = len(p)\n if n == 4:\n p[0] = ('BitNames', p[1][1] + [p[3]])\n elif n == 2:\n p[0] = ('BitNames', [p[1]])", "response": "BitNames : BitNames | LOWERCASE_IDENTIFIER\n | LOWERCASE_IDENTIFIER\n | LOWERCASE_IDENTIFIER"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef p_Objects(self, p):\n n = len(p)\n if n == 4:\n p[0] = ('Objects', p[1][1] + [p[3]])\n elif n == 2:\n p[0] = ('Objects', [p[1]])", "response": "Object objects | Objects | Object | Object | Object | Object |"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef p_Notifications(self, p):\n n = len(p)\n if n == 4:\n p[0] = ('Notifications', p[1][1] + [p[3]])\n elif n == 2:\n p[0] = ('Notifications', [p[1]])", "response": "Notifications | Notifications | Notification\n | Notification | Notification"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef p_subidentifiers(self, p):\n n = len(p)\n if n == 3:\n p[0] = p[1] + [p[2]]\n elif n == 2:\n p[0] = [p[1]]", "response": "subidentifiers is a list of subidentifiers"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef p_subidentifier(self, p):\n n = len(p)\n if n == 2:\n p[0] = p[1]\n elif n == 5:\n # NOTE: we are not creating new symbol p[1] because formally\n # it is not defined in *this* MIB\n p[0] = (p[1], p[3])", "response": "subidentifier : fuzzy_lowercase_identifier\n | NUMBER\n | LOWERCASE_IDENTIFIER '(' NUMBER ')"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef p_subidentifiers_defval(self, p):\n n = len(p)\n if n == 3:\n p[0] = ('subidentifiers_defval', p[1][1] + [p[2]])\n elif n == 2:\n p[0] = ('subidentifiers_defval', [p[1]])", "response": "subidentifiers_defval | subidentifier_defval\n | subidentifier_defval"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef p_subidentifier_defval(self, p):\n n = len(p)\n if n == 2:\n p[0] = ('subidentifier_defval', p[1])\n elif n == 5:\n p[0] = ('subidentifier_defval', p[1], p[3])", "response": "subidentifier_defval : LOWERCASE_IDENTIFIER '(' NUMBER ')'\n | NUMBER"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef p_objectGroupClause(self, p):\n p[0] = ('objectGroupClause',\n p[1], # id\n p[3], # objects\n p[5], # status\n (p[6], p[7]), # description\n p[8], # reference\n p[11])", "response": "P objectGroupClause - objectGroupClause"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef p_notificationGroupClause(self, p):\n p[0] = ('notificationGroupClause',\n p[1], # id\n p[3], # notifications\n p[5], # status\n (p[6], p[7]), # description\n p[8], # reference\n p[11])", "response": "p_notificationGroupClause - Puts the values in the object p into the p_notificationGroupClause field."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef p_ComplianceModule(self, p):\n objects = p[3] and p[3][1] or []\n objects += p[4] and p[4][1] or []\n p[0] = (p[2], # ModuleName\n objects)", "response": "A ComplianceModule is a section of the XML."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef p_Compliances(self, p):\n n = len(p)\n if n == 3:\n p[0] = p[1] and p[2] and ('Compliances', p[1][1] + [p[2]]) or p[1]\n elif n == 2:\n p[0] = p[1] and ('Compliances', [p[1]]) or None", "response": "Compliances is a list of Compliances"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef p_notificationTypeClause(self, p):\n p[0] = ('notificationTypeClause', p[1], # id\n # p[2], # NOTIFICATION_TYPE\n p[3], # NotificationObjectsPart\n p[5], # status\n (p[6], p[7]), # description\n p[8], # Reference\n p[11])", "response": "p_notificationTypeClause - > SET p_notificationTypeClause"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef p_trapTypeClause(self, p):\n # libsmi: TODO: range of number?\n p[0] = ('trapTypeClause', p[1], # fuzzy_lowercase_identifier\n # p[2], # TRAP_TYPE\n p[3], # EnterprisePart (objectIdentifier)\n p[4], # VarPart\n p[5], # description\n p[6], # reference\n p[8])", "response": "trapTypeClause : fuzzy_lowercase_identifier TRAP_TYPE VarPart DescrPart ReferPart COLON_EQUAL NUMBER"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef p_CreationPart(self, p):\n n = len(p)\n if n == 5:\n p[0] = (p[1], p[3])", "response": "CreationPart is a tuple of 2 - tuples where 1 - 2 is the name of the object and 3 - 3 is the id of the object."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef AIC(N, rho, k):\n from numpy import log, array\n #k+1 #todo check convention. agrees with octave\n\n res = N * log(array(rho)) + 2.* (array(k)+1)\n return res", "response": "r Akaike Information Criterion for the given sample size and size."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ncorrects Akaike information criterion .. math :: AICc = log \\ rho_k + 2 \\ frac{N - k - 1}{N - k - 2 }", "response": "def AICc(N, rho, k, norm=True):\n r\"\"\"corrected Akaike information criterion\n\n .. math:: AICc(k) = log(\\rho_k) + 2 \\frac{k+1}{N-k-2}\n\n\n :validation: double checked versus octave.\n \"\"\"\n from numpy import log, array\n p = k #todo check convention. agrees with octave\n res = log(rho) + 2. * (p+1) / (N-p-2)\n return res"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef KIC(N, rho, k):\n from numpy import log, array\n res = log(rho) + 3. * (k+1.) /float(N)\n return res", "response": "r Kullback information criterion"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef AKICc(N, rho, k):\n from numpy import log, array\n p = k\n res = log(rho) + p/N/(N-p) + (3.-(p+2.)/N) * (p+1.) / (N-p-2.)\n return res", "response": "approximate corrected Kullback information"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef FPE(N,rho, k=None):\n #k #todo check convention. agrees with octave\n fpe = rho * (N + k + 1.) / (N- k -1)\n return fpe", "response": "rFinal prediction error criterion\n .. math :: FPE = rho^N"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef CAT(N, rho, k):\n from numpy import zeros, arange\n cat = zeros(len(rho))\n for p in arange(1, len(rho)+1):\n rho_p = float(N)/(N-p)*rho[p-1]\n s = 0\n for j in range(1, p+1):\n rho_j = float(N)/(N-j)*rho[j-1]\n s = s + 1./rho_j\n #print(s, s/float(N), 1./rho_p)\n cat[p-1] = s/float(N) - 1./rho_p\n return cat", "response": "rCriterion Autoregressive Transfer Function"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef generate_gallery_rst(app):\n try:\n plot_gallery = eval(app.builder.config.plot_gallery)\n except TypeError:\n plot_gallery = bool(app.builder.config.plot_gallery)\n\n gallery_conf.update(app.config.sphinx_gallery_conf)\n gallery_conf.update(plot_gallery=plot_gallery)\n gallery_conf.update(abort_on_example_error=app.builder.config.abort_on_example_error)\n\n # this assures I can call the config in other places\n app.config.sphinx_gallery_conf = gallery_conf\n app.config.html_static_path.append(glr_path_static())\n\n clean_gallery_out(app.builder.outdir)\n\n examples_dirs = gallery_conf['examples_dirs']\n gallery_dirs = gallery_conf['gallery_dirs']\n\n if not isinstance(examples_dirs, list):\n examples_dirs = [examples_dirs]\n if not isinstance(gallery_dirs, list):\n gallery_dirs = [gallery_dirs]\n\n mod_examples_dir = os.path.relpath(gallery_conf['mod_example_dir'],\n app.builder.srcdir)\n seen_backrefs = set()\n\n for examples_dir, gallery_dir in zip(examples_dirs, gallery_dirs):\n examples_dir = os.path.relpath(examples_dir,\n app.builder.srcdir)\n gallery_dir = os.path.relpath(gallery_dir,\n app.builder.srcdir)\n\n for workdir in [examples_dir, gallery_dir, mod_examples_dir]:\n if not os.path.exists(workdir):\n os.makedirs(workdir)\n\n # we create an index.rst with all examples\n fhindex = open(os.path.join(gallery_dir, 'index.rst'), 'w')\n # Here we don't use an os.walk, but we recurse only twice: flat is\n # better than nested.\n fhindex.write(generate_dir_rst(examples_dir, gallery_dir, gallery_conf,\n seen_backrefs))\n for directory in sorted(os.listdir(examples_dir)):\n if os.path.isdir(os.path.join(examples_dir, directory)):\n src_dir = os.path.join(examples_dir, directory)\n target_dir = os.path.join(gallery_dir, directory)\n fhindex.write(generate_dir_rst(src_dir, target_dir,\n gallery_conf,\n seen_backrefs))\n fhindex.flush()", "response": "Generate the main examples gallery reStructuredText containing all the examples"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef setup(app):\n app.add_config_value('plot_gallery', True, 'html')\n app.add_config_value('abort_on_example_error', False, 'html')\n app.add_config_value('sphinx_gallery_conf', gallery_conf, 'html')\n app.add_stylesheet('gallery.css')\n\n app.connect('builder-inited', generate_gallery_rst)\n\n app.connect('build-finished', embed_code_links)", "response": "Setup sphinx - gallery extension"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncompute the cross - correlation of two random processes of length N.", "response": "def xcorr(x, y=None, maxlags=None, norm='biased'):\n \"\"\"Cross-correlation using numpy.correlate\n\n Estimates the cross-correlation (and autocorrelation) sequence of a random\n process of length N. By default, there is no normalisation and the output\n sequence of the cross-correlation has a length 2*N+1.\n\n :param array x: first data array of length N\n :param array y: second data array of length N. If not specified, computes the\n autocorrelation.\n :param int maxlags: compute cross correlation between [-maxlags:maxlags]\n when maxlags is not specified, the range of lags is [-N+1:N-1].\n :param str option: normalisation in ['biased', 'unbiased', None, 'coeff']\n\n The true cross-correlation sequence is\n\n .. math:: r_{xy}[m] = E(x[n+m].y^*[n]) = E(x[n].y^*[n-m])\n\n However, in practice, only a finite segment of one realization of the\n infinite-length random process is available.\n\n The correlation is estimated using numpy.correlate(x,y,'full').\n Normalisation is handled by this function using the following cases:\n\n * 'biased': Biased estimate of the cross-correlation function\n * 'unbiased': Unbiased estimate of the cross-correlation function\n * 'coeff': Normalizes the sequence so the autocorrelations at zero\n lag is 1.0.\n\n :return:\n * a numpy.array containing the cross-correlation sequence (length 2*N-1)\n * lags vector\n\n .. note:: If x and y are not the same length, the shorter vector is\n zero-padded to the length of the longer vector.\n\n .. rubric:: Examples\n\n .. doctest::\n\n >>> from spectrum import xcorr\n >>> x = [1,2,3,4,5]\n >>> c, l = xcorr(x,x, maxlags=0, norm='biased')\n >>> c\n array([ 11.])\n\n .. seealso:: :func:`CORRELATION`.\n \"\"\"\n N = len(x)\n if y is None:\n y = x\n assert len(x) == len(y), 'x and y must have the same length. Add zeros if needed'\n\n if maxlags is None:\n maxlags = N-1\n lags = np.arange(0, 2*N-1)\n else:\n assert maxlags <= N, 'maxlags must be less than data length'\n lags = np.arange(N-maxlags-1, N+maxlags)\n\n res = np.correlate(x, y, mode='full')\n\n if norm == 'biased':\n Nf = float(N)\n res = res[lags] / float(N) # do not use /= !!\n elif norm == 'unbiased':\n res = res[lags] / (float(N)-abs(np.arange(-N+1, N)))[lags]\n elif norm == 'coeff':\n Nf = float(N)\n rms = pylab_rms_flat(x) * pylab_rms_flat(y)\n res = res[lags] / rms / Nf\n else:\n res = res[lags]\n\n lags = np.arange(-maxlags, maxlags+1)\n return res, lags"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nfinds the minimum eigenvalue of a Hermitian Toeplitz matrix The classical power method is used together with a fast Toeplitz equation solution routine. The eigenvector is normalized to unit length. :param T0: Scalar corresponding to real matrix element t(0) :param T: Array of M complex matrix elements t(1),...,t(M) C from the left column of the Toeplitz matrix :param TOL: Real scalar tolerance; routine exits when [ EVAL(k) - EVAL(k-1) ]/EVAL(k-1) < TOL , where the index k denotes the iteration number. :return: * EVAL - Real scalar denoting the minimum eigenvalue of matrix * EVEC - Array of M complex eigenvector elements associated .. note:: * External array T must be dimensioned >= M * array EVEC must be >= M+1 * Internal array E must be dimensioned >= M+1 . * **dependencies** * :meth:`spectrum.toeplitz.HERMTOEP`", "response": "def MINEIGVAL(T0, T, TOL):\n \"\"\"Finds the minimum eigenvalue of a Hermitian Toeplitz matrix\n\n The classical power method is used together with a fast Toeplitz\n equation solution routine. The eigenvector is normalized to unit length.\n\n :param T0: Scalar corresponding to real matrix element t(0)\n :param T: Array of M complex matrix elements t(1),...,t(M) C from the left column of the Toeplitz matrix\n :param TOL: Real scalar tolerance; routine exits when [ EVAL(k) - EVAL(k-1) ]/EVAL(k-1) < TOL , where the index k denotes the iteration number.\n\n :return:\n * EVAL - Real scalar denoting the minimum eigenvalue of matrix\n * EVEC - Array of M complex eigenvector elements associated\n\n\n .. note::\n * External array T must be dimensioned >= M\n * array EVEC must be >= M+1\n * Internal array E must be dimensioned >= M+1 . \n\n * **dependencies**\n * :meth:`spectrum.toeplitz.HERMTOEP`\n \"\"\"\n M = len(T)\n eigval = 10\n eigvalold = 1\n eigvec = numpy.zeros(M+1, dtype=complex)\n for k in range(0,M+1):\n eigvec[k] = 1+0j\n it=0\n #print 'initialisation',T0, T, eigval, eigvec\n maxit = 15\n while abs(eigvalold-eigval)>TOL*eigvalold and it>> from spectrum import ac2poly\n >>> from numpy import array\n >>> r = [5, -2, 1.01]\n >>> ar, e = ac2poly(r)\n >>> ar\n array([ 1. , 0.38, -0.05])\n >>> e\n 4.1895000000000007\n\n \"\"\"\n a, e, _c = LEVINSON(data)\n a = numpy.insert(a, 0, 1)\n return a, e"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef rc2poly(kr, r0=None):\n # Initialize the recursion\n from .levinson import levup\n p = len(kr) #% p is the order of the prediction polynomial.\n a = numpy.array([1, kr[0]]) #% a is a true polynomial.\n e = numpy.zeros(len(kr))\n\n if r0 is None:\n e0 = 0\n else:\n e0 = r0\n\n e[0] = e0 * (1. - numpy.conj(numpy.conjugate(kr[0])*kr[0]))\n\n # Continue the recursion for k=2,3,...,p, where p is the order of the\n # prediction polynomial.\n\n for k in range(1, p):\n [a, e[k]] = levup(a, kr[k], e[k-1])\n\n efinal = e[-1]\n return a, efinal", "response": "convert reflection coefficients to prediction filter polynomial"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef rc2ac(k, R0):\n [a,efinal] = rc2poly(k, R0)\n R, u, kr, e = rlevinson(a, efinal)\n return R", "response": "Convert reflection coefficients to autocorrelation sequence."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef rc2is(k):\n assert numpy.isrealobj(k), 'Inverse sine parameters not defined for complex reflection coefficients.'\n if max(numpy.abs(k)) >= 1:\n raise ValueError('All reflection coefficients should have magnitude less than unity.')\n\n return (2/numpy.pi)*numpy.arcsin(k)", "response": "Convert complex reflection coefficients to inverse sine parameters."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nconvert complex reflection coefficients to log area ratios.", "response": "def rc2lar(k):\n \"\"\"Convert reflection coefficients to log area ratios.\n\n :param k: reflection coefficients\n :return: inverse sine parameters\n\n The log area ratio is defined by G = log((1+k)/(1-k)) , where the K\n parameter is the reflection coefficient.\n\n .. seealso:: :func:`lar2rc`, :func:`rc2poly`, :func:`rc2ac`, :func:`rc2ic`.\n\n :References:\n [1] J. Makhoul, \"Linear Prediction: A Tutorial Review,\" Proc. IEEE, Vol.63, No.4, pp.561-580, Apr 1975.\n\n \"\"\"\n assert numpy.isrealobj(k), 'Log area ratios not defined for complex reflection coefficients.'\n if max(numpy.abs(k)) >= 1:\n raise ValueError('All reflection coefficients should have magnitude less than unity.')\n\n # Use the relation, atanh(x) = (1/2)*log((1+k)/(1-k))\n return -2 * numpy.arctanh(-numpy.array(k))"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nconverts log area ratios to reflection coefficients.", "response": "def lar2rc(g):\n \"\"\"Convert log area ratios to reflection coefficients.\n\n :param g: log area ratios\n :returns: the reflection coefficients\n\n .. seealso: :func:`rc2lar`, :func:`poly2rc`, :func:`ac2rc`, :func:`is2rc`.\n\n :References:\n [1] J. Makhoul, \"Linear Prediction: A Tutorial Review,\" Proc. IEEE, Vol.63, No.4, pp.561-580, Apr 1975.\n\n \"\"\"\n assert numpy.isrealobj(g), 'Log area ratios not defined for complex reflection coefficients.'\n # Use the relation, tanh(x) = (1-exp(2x))/(1+exp(2x))\n return -numpy.tanh(-numpy.array(g)/2)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef lsf2poly(lsf):\n # Reference: A.M. Kondoz, \"Digital Speech: Coding for Low Bit Rate Communications\n # Systems\" John Wiley & Sons 1994 ,Chapter 4\n\n # Line spectral frequencies must be real.\n\n lsf = numpy.array(lsf)\n\n if max(lsf) > numpy.pi or min(lsf) < 0:\n raise ValueError('Line spectral frequencies must be between 0 and pi.')\n\n p = len(lsf) # model order\n\n # Form zeros using the LSFs and unit amplitudes\n z = numpy.exp(1.j * lsf)\n\n # Separate the zeros to those belonging to P and Q\n rQ = z[0::2]\n rP = z[1::2]\n\n # Include the conjugates as well\n rQ = numpy.concatenate((rQ, rQ.conjugate()))\n rP = numpy.concatenate((rP, rP.conjugate()))\n\n # Form the polynomials P and Q, note that these should be real\n Q = numpy.poly(rQ);\n P = numpy.poly(rP);\n\n # Form the sum and difference filters by including known roots at z = 1 and\n # z = -1\n\n if p%2:\n # Odd order: z = +1 and z = -1 are roots of the difference filter, P1(z)\n P1 = numpy.convolve(P, [1, 0, -1])\n Q1 = Q\n else:\n # Even order: z = -1 is a root of the sum filter, Q1(z) and z = 1 is a\n # root of the difference filter, P1(z)\n P1 = numpy.convolve(P, [1, -1])\n Q1 = numpy.convolve(Q, [1, 1])\n\n # Prediction polynomial is formed by averaging P1 and Q1\n\n a = .5 * (P1+Q1)\n return a[0:-1:1]", "response": "Convert line spectral frequencies to prediction filter coefficients."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef poly2lsf(a):\n\n #Line spectral frequencies are not defined for complex polynomials.\n\n # Normalize the polynomial\n\n a = numpy.array(a)\n if a[0] != 1:\n a/=a[0]\n\n if max(numpy.abs(numpy.roots(a))) >= 1.0:\n error('The polynomial must have all roots inside of the unit circle.');\n\n\n # Form the sum and differnce filters\n\n p = len(a)-1 # The leading one in the polynomial is not used\n a1 = numpy.concatenate((a, numpy.array([0])))\n a2 = a1[-1::-1]\n P1 = a1 - a2 # Difference filter\n Q1 = a1 + a2 # Sum Filter\n\n # If order is even, remove the known root at z = 1 for P1 and z = -1 for Q1\n # If odd, remove both the roots from P1\n\n if p%2: # Odd order\n P, r = deconvolve(P1,[1, 0 ,-1])\n Q = Q1\n else: # Even order\n P, r = deconvolve(P1, [1, -1])\n Q, r = deconvolve(Q1, [1, 1])\n\n rP = numpy.roots(P)\n rQ = numpy.roots(Q)\n\n aP = numpy.angle(rP[1::2])\n aQ = numpy.angle(rQ[1::2])\n\n lsf = sorted(numpy.concatenate((-aP,-aQ)))\n\n return lsf", "response": "Convert a prediction polynomial to line spectral frequencies LSF."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _swapsides(data):\n N = len(data)\n return np.concatenate((data[N//2+1:], data[0:N//2]))", "response": "get the list of swapsides"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nconvert a one - sided PSD to a twosided PSD", "response": "def twosided_2_onesided(data):\n \"\"\"Convert a one-sided PSD to a twosided PSD\n\n In order to keep the power in the onesided PSD the same\n as in the twosided version, the onesided values are twice\n as much as in the input data (except for the zero-lag value).\n\n ::\n\n >>> twosided_2_onesided([10, 2,3,3,2,8])\n array([ 10., 4., 6., 8.])\n\n \"\"\"\n assert len(data) % 2 == 0\n N = len(data)\n psd = np.array(data[0:N//2+1]) * 2.\n psd[0] /= 2.\n psd[-1] = data[-1]\n return psd"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nconverting a two - sided PSD to a one - sided PSD", "response": "def onesided_2_twosided(data):\n \"\"\"Convert a two-sided PSD to a one-sided PSD\n\n In order to keep the power in the twosided PSD the same\n as in the onesided version, the twosided values are 2 times\n lower than the input data (except for the zero-lag and N-lag\n values).\n\n ::\n\n >>> twosided_2_onesided([10, 4, 6, 8])\n array([ 10., 2., 3., 3., 2., 8.])\n\n \"\"\"\n psd = np.concatenate((data[0:-1], cshift(data[-1:0:-1], -1)))/2.\n psd[0] *= 2.\n psd[-1] *= 2.\n return psd"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef twosided_2_centerdc(data):\n N = len(data)\n # could us int() or // in python 3\n newpsd = np.concatenate((cshift(data[N//2:], 1), data[0:N//2]))\n newpsd[0] = data[-1]\n return newpsd", "response": "Convert a two - sided PSD to a center - dc PSD"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nconverts a center - dc PSD to a twosided PSD", "response": "def centerdc_2_twosided(data):\n \"\"\"Convert a center-dc PSD to a twosided PSD\"\"\"\n N = len(data)\n newpsd = np.concatenate((data[N//2:], (cshift(data[0:N//2], -1))))\n return newpsd"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nbuilding a symmetric vector out of stricly positive lag vector and zero - lag .. doctest::", "response": "def _twosided_zerolag(data, zerolag):\n \"\"\"Build a symmetric vector out of stricly positive lag vector and zero-lag\n\n .. doctest::\n\n >>> data = [3,2,1]\n >>> zerolag = 4\n >>> twosided_zerolag(data, zerolag)\n array([1, 2, 3, 4, 3, 2, 1])\n\n .. seealso:: Same behaviour as :func:`twosided_zerolag`\n \"\"\"\n res = twosided(np.insert(data, 0, zerolag))\n return res"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef spectrum_data(filename):\n import os\n import pkg_resources\n info = pkg_resources.get_distribution('spectrum')\n location = info.location\n\n # first try develop mode\n share = os.sep.join([location, \"spectrum\", 'data'])\n filename2 = os.sep.join([share, filename])\n if os.path.exists(filename2):\n return filename2\n else:\n raise Exception('unknown file %s' % filename2)", "response": "Simple utility to retrieve data sets from a spectrum file"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef plot(self, **kargs):\n from pylab import plot, linspace, xlabel, ylabel, grid\n time = linspace(1*self.dt, self.N*self.dt, self.N)\n plot(time, self.data, **kargs)\n xlabel('Time')\n ylabel('Amplitude')\n grid(True)", "response": "Plot the data set using the sampling information to set the x - axis\n correctly."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef readwav(filename):\n from scipy.io.wavfile import read as readwav\n samplerate, signal = readwav(filename)\n return signal, samplerate", "response": "Read a WAV file and returns the data and sample rate of the next page."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef pmtm(x, NW=None, k=None, NFFT=None, e=None, v=None, method='adapt', show=False):\n assert method in ['adapt','eigen','unity']\n\n N = len(x)\n\n # if dpss not provided, compute them\n if e is None and v is None:\n if NW is not None:\n [tapers, eigenvalues] = dpss(N, NW, k=k)\n else:\n raise ValueError(\"NW must be provided (e.g. 2.5, 3, 3.5, 4\")\n elif e is not None and v is not None:\n eigenvalues = e[:]\n tapers = v[:]\n else:\n raise ValueError(\"if e provided, v must be provided as well and viceversa.\")\n nwin = len(eigenvalues) # length of the eigen values vector to be used later\n\n # set the NFFT\n if NFFT==None:\n NFFT = max(256, 2**nextpow2(N))\n\n Sk_complex = np.fft.fft(np.multiply(tapers.transpose(), x), NFFT)\n Sk = abs(Sk_complex)**2\n\n # si nfft smaller thqn N, cut otherwise add wero.\n # compute\n if method in ['eigen', 'unity']:\n if method == 'unity':\n weights = np.ones((nwin, 1))\n elif method == 'eigen':\n # The S_k spectrum can be weighted by the eigenvalues, as in Park et al.\n weights = np.array([_x/float(i+1) for i,_x in enumerate(eigenvalues)])\n weights = weights.reshape(nwin,1)\n\n elif method == 'adapt':\n # This version uses the equations from [2] (P&W pp 368-370).\n\n # Wrap the data modulo nfft if N > nfft\n sig2 = np.dot(x, x) / float(N)\n Sk = abs(np.fft.fft(np.multiply(tapers.transpose(), x), NFFT))**2\n Sk = Sk.transpose()\n S = (Sk[:,0] + Sk[:,1]) / 2 # Initial spectrum estimate\n S = S.reshape(NFFT, 1)\n Stemp = np.zeros((NFFT,1))\n S1 = np.zeros((NFFT,1))\n # Set tolerance for acceptance of spectral estimate:\n tol = 0.0005 * sig2 / float(NFFT)\n i = 0\n a = sig2 * (1 - eigenvalues)\n\n # converges very quickly but for safety; set i<100\n while sum(np.abs(S-S1))/NFFT > tol and i<100:\n i = i + 1\n # calculate weights\n b1 = np.multiply(S, np.ones((1,nwin)))\n b2 = np.multiply(S,eigenvalues.transpose()) + np.ones((NFFT,1))*a.transpose()\n b = b1/b2\n\n # calculate new spectral estimate\n wk=(b**2)*(np.ones((NFFT,1))*eigenvalues.transpose())\n S1 = sum(wk.transpose()*Sk.transpose())/ sum(wk.transpose())\n S1 = S1.reshape(NFFT, 1)\n Stemp = S1\n S1 = S\n S = Stemp # swap S and S1\n weights=wk\n\n if show is True:\n from pylab import semilogy\n if method == \"adapt\":\n Sk = np.mean(Sk * weights, axis=1)\n else:\n Sk = np.mean(Sk * weights, axis=0)\n semilogy(Sk)\n\n return Sk_complex, weights, eigenvalues", "response": "Multitapering spectral estimation of a set of data."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _other_dpss_method(N, NW, Kmax):\n # here we want to set up an optimization problem to find a sequence\n # whose energy is maximally concentrated within band [-W,W].\n # Thus, the measure lambda(T,W) is the ratio between the energy within\n # that band, and the total energy. This leads to the eigen-system\n # (A - (l1)I)v = 0, where the eigenvector corresponding to the largest\n # eigenvalue is the sequence with maximally concentrated energy. The\n # collection of eigenvectors of this system are called Slepian sequences,\n # or discrete prolate spheroidal sequences (DPSS). Only the first K,\n # K = 2NW/dt orders of DPSS will exhibit good spectral concentration\n # [see http://en.wikipedia.org/wiki/Spectral_concentration_problem]\n\n # Here I set up an alternative symmetric tri-diagonal eigenvalue problem\n # such that\n # (B - (l2)I)v = 0, and v are our DPSS (but eigenvalues l2 != l1)\n # the main diagonal = ([N-1-2*t]/2)**2 cos(2PIW), t=[0,1,2,...,N-1]\n # and the first off-diangonal = t(N-t)/2, t=[1,2,...,N-1]\n # [see Percival and Walden, 1993]\n from scipy import linalg as la\n Kmax = int(Kmax)\n W = float(NW)/N\n ab = np.zeros((2,N), 'd')\n nidx = np.arange(N)\n ab[0,1:] = nidx[1:]*(N-nidx[1:])/2.\n ab[1] = ((N-1-2*nidx)/2.)**2 * np.cos(2*np.pi*W)\n # only calculate the highest Kmax-1 eigenvectors\n l,v = la.eig_banded(ab, select='i', select_range=(N-Kmax, N-1))\n dpss = v.transpose()[::-1]\n\n # By convention (Percival and Walden, 1993 pg 379)\n # * symmetric tapers (k=0,2,4,...) should have a positive average.\n # * antisymmetric tapers should begin with a positive lobe\n fix_symmetric = (dpss[0::2].sum(axis=1) < 0)\n for i, f in enumerate(fix_symmetric):\n if f:\n dpss[2*i] *= -1\n fix_skew = (dpss[1::2,1] < 0)\n for i, f in enumerate(fix_skew):\n if f:\n dpss[2*i+1] *= -1\n\n # Now find the eigenvalues of the original\n # Use the autocovariance sequence technique from Percival and Walden, 1993\n # pg 390\n # XXX : why debias false? it's all messed up o.w., even with means\n # on the order of 1e-2\n acvs = _autocov(dpss, debias=False) * N\n r = 4*W*np.sinc(2*W*nidx)\n r[0] = 2*W\n eigvals = np.dot(acvs, r)\n return dpss, eigvals", "response": "This method is used by other functions to get the Discrete Prolate Spheroidal Sequences of orders 0 Kmax - 1"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _autocov(s, **kwargs):\n # only remove the mean once, if needed\n debias = kwargs.pop('debias', True)\n axis = kwargs.get('axis', -1)\n if debias:\n s = _remove_bias(s, axis)\n kwargs['debias'] = False\n return _crosscov(s, s, **kwargs)", "response": "Returns the autocovariance of signal s at all lags."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _crosscov(x, y, axis=-1, all_lags=False, debias=True):\n if x.shape[axis] != y.shape[axis]:\n raise ValueError(\n 'crosscov() only works on same-length sequences for now'\n )\n if debias:\n x = _remove_bias(x, axis)\n y = _remove_bias(y, axis)\n slicing = [slice(d) for d in x.shape]\n slicing[axis] = slice(None,None,-1)\n sxy = _fftconvolve(x, y[tuple(slicing)], axis=axis, mode='full')\n N = x.shape[axis]\n sxy /= N\n if all_lags:\n return sxy\n slicing[axis] = slice(N-1,2*N-1)\n return sxy[tuple(slicing)]", "response": "Returns the crosscovariance sequence between two ndarrays."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn the crosscorrelation sequence between two ndarrays.", "response": "def _crosscorr(x, y, **kwargs):\n \"\"\"\n Returns the crosscorrelation sequence between two ndarrays.\n This is performed by calling fftconvolve on x, y[::-1]\n\n Parameters\n\n\n x: ndarray\n y: ndarray\n axis: time axis\n all_lags: {True/False}\n whether to return all nonzero lags, or to clip the length of r_xy\n to be the length of x and y. If False, then the zero lag correlation\n is at index 0. Otherwise, it is found at (len(x) + len(y) - 1)/2\n\n Notes\n\n\n cross correlation is defined as\n rxy[k] := E{X[t]*Y[t+k]}/(E{X*X}E{Y*Y})**.5,\n where X,Y are zero mean random processes. It is the noramlized cross\n covariance.\n \"\"\"\n sxy = _crosscov(x, y, **kwargs)\n # estimate sigma_x, sigma_y to normalize\n sx = np.std(x)\n sy = np.std(y)\n return sxy/(sx*sy)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _remove_bias(x, axis):\n \"Subtracts an estimate of the mean from signal x at axis\"\n padded_slice = [slice(d) for d in x.shape]\n padded_slice[axis] = np.newaxis\n mn = np.mean(x, axis=axis)\n return x - mn[tuple(padded_slice)]", "response": "Subtracts an estimate of the mean from signal x at axis"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nseparating filename content between docstring and the rest", "response": "def get_docstring_and_rest(filename):\n \"\"\"Separate `filename` content between docstring and the rest\n\n Strongly inspired from ast.get_docstring.\n\n Returns\n -------\n docstring: str\n docstring of `filename`\n rest: str\n `filename` content without the docstring\n \"\"\"\n with open(filename) as f:\n content = f.read()\n\n node = ast.parse(content)\n if not isinstance(node, ast.Module):\n raise TypeError(\"This function only supports modules. \"\n \"You provided {0}\".format(node.__class__.__name__))\n if node.body and isinstance(node.body[0], ast.Expr) and \\\n isinstance(node.body[0].value, ast.Str):\n docstring_node = node.body[0]\n docstring = docstring_node.value.s\n # This get the content of the file after the docstring last line\n # Note: 'maxsplit' argument is not a keyword argument in python2\n rest = content.split('\\n', docstring_node.lineno)[-1]\n return docstring, rest\n else:\n raise ValueError(('Could not find docstring in file \"{0}\". '\n 'A docstring is required by sphinx-gallery')\n .format(filename))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn list with source file separated into code and text blocks.", "response": "def split_code_and_text_blocks(source_file):\n \"\"\"Return list with source file separated into code and text blocks.\n\n Returns\n -------\n blocks : list of (label, content)\n List where each element is a tuple with the label ('text' or 'code'),\n and content string of block.\n \"\"\"\n docstring, rest_of_content = get_docstring_and_rest(source_file)\n\n blocks = [('text', docstring)]\n\n pattern = re.compile(\n r'(?P^#{20,}.*)\\s(?P(?:^#.*\\s)*)',\n flags=re.M)\n\n pos_so_far = 0\n for match in re.finditer(pattern, rest_of_content):\n match_start_pos, match_end_pos = match.span()\n code_block_content = rest_of_content[pos_so_far:match_start_pos]\n text_content = match.group('text_content')\n sub_pat = re.compile('^#', flags=re.M)\n text_block_content = dedent(re.sub(sub_pat, '', text_content))\n if code_block_content.strip():\n blocks.append(('code', code_block_content))\n if text_block_content.strip():\n blocks.append(('text', text_block_content))\n pos_so_far = match_end_pos\n\n remaining_content = rest_of_content[pos_so_far:]\n if remaining_content.strip():\n blocks.append(('code', remaining_content))\n\n return blocks"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns reStructuredText code block from code string", "response": "def codestr2rst(codestr, lang='python'):\n \"\"\"Return reStructuredText code block from code string\"\"\"\n code_directive = \"\\n.. code-block:: {0}\\n\\n\".format(lang)\n indented_block = indent(codestr, ' ' * 4)\n return code_directive + indented_block"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef extract_intro(filename):\n\n docstring, _ = get_docstring_and_rest(filename)\n\n # lstrip is just in case docstring has a '\\n\\n' at the beginning\n paragraphs = docstring.lstrip().split('\\n\\n')\n if len(paragraphs) > 1:\n first_paragraph = re.sub('\\n', ' ', paragraphs[1])\n first_paragraph = (first_paragraph[:95] + '...'\n if len(first_paragraph) > 95 else first_paragraph)\n else:\n raise ValueError(\n \"Example docstring should have a header for the example title \"\n \"and at least a paragraph explaining what the example is about. \"\n \"Please check the example file:\\n {}\\n\".format(filename))\n\n return first_paragraph", "response": "Extract the first paragraph of module - level docstring. max : 95 char"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns md5sum of file", "response": "def get_md5sum(src_file):\n \"\"\"Returns md5sum of file\"\"\"\n\n with open(src_file, 'r') as src_data:\n src_content = src_data.read()\n\n # data needs to be encoded in python3 before hashing\n if sys.version_info[0] == 3:\n src_content = src_content.encode('utf-8')\n\n src_md5 = hashlib.md5(src_content).hexdigest()\n return src_md5"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef check_md5sum_change(src_file):\n\n src_md5 = get_md5sum(src_file)\n\n src_md5_file = src_file + '.md5'\n src_file_changed = True\n if os.path.exists(src_md5_file):\n with open(src_md5_file, 'r') as file_checksum:\n ref_md5 = file_checksum.read()\n if src_md5 == ref_md5:\n src_file_changed = False\n\n if src_file_changed:\n with open(src_md5_file, 'w') as file_checksum:\n file_checksum.write(src_md5)\n\n return src_file_changed", "response": "Returns True if src_file has a different md5sum"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _plots_are_current(src_file, image_file):\n\n first_image_file = image_file.format(1)\n has_image = os.path.exists(first_image_file)\n src_file_changed = check_md5sum_change(src_file)\n\n return has_image and not src_file_changed", "response": "Test existence of image file and no change in md5sum of\n example"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nsaves all open matplotlib figures of the example code - block.", "response": "def save_figures(image_path, fig_count, gallery_conf):\n \"\"\"Save all open matplotlib figures of the example code-block\n\n Parameters\n ----------\n image_path : str\n Path where plots are saved (format string which accepts figure number)\n fig_count : int\n Previous figure number count. Figure number add from this number\n\n Returns\n -------\n list of strings containing the full path to each figure\n \"\"\"\n figure_list = []\n\n fig_managers = matplotlib._pylab_helpers.Gcf.get_all_fig_managers()\n for fig_mngr in fig_managers:\n # Set the fig_num figure as the current figure as we can't\n # save a figure that's not the current figure.\n fig = plt.figure(fig_mngr.num)\n kwargs = {}\n to_rgba = matplotlib.colors.colorConverter.to_rgba\n for attr in ['facecolor', 'edgecolor']:\n fig_attr = getattr(fig, 'get_' + attr)()\n default_attr = matplotlib.rcParams['figure.' + attr]\n if to_rgba(fig_attr) != to_rgba(default_attr):\n kwargs[attr] = fig_attr\n\n current_fig = image_path.format(fig_count + fig_mngr.num)\n fig.savefig(current_fig, **kwargs)\n figure_list.append(current_fig)\n\n if gallery_conf.get('find_mayavi_figures', False):\n from mayavi import mlab\n e = mlab.get_engine()\n last_matplotlib_fig_num = len(figure_list)\n total_fig_num = last_matplotlib_fig_num + len(e.scenes)\n mayavi_fig_nums = range(last_matplotlib_fig_num, total_fig_num)\n\n for scene, mayavi_fig_num in zip(e.scenes, mayavi_fig_nums):\n current_fig = image_path.format(mayavi_fig_num)\n mlab.savefig(current_fig, figure=scene)\n # make sure the image is not too large\n scale_image(current_fig, current_fig, 850, 999)\n figure_list.append(current_fig)\n mlab.close(all=True)\n\n return figure_list"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef scale_image(in_fname, out_fname, max_width, max_height):\n # local import to avoid testing dependency on PIL:\n try:\n from PIL import Image\n except ImportError:\n import Image\n img = Image.open(in_fname)\n width_in, height_in = img.size\n scale_w = max_width / float(width_in)\n scale_h = max_height / float(height_in)\n\n if height_in * scale_w <= max_height:\n scale = scale_w\n else:\n scale = scale_h\n\n if scale >= 1.0 and in_fname == out_fname:\n return\n\n width_sc = int(round(scale * width_in))\n height_sc = int(round(scale * height_in))\n\n # resize the image\n img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)\n\n # insert centered\n thumb = Image.new('RGB', (max_width, max_height), (255, 255, 255))\n pos_insert = ((max_width - width_sc) // 2, (max_height - height_sc) // 2)\n thumb.paste(img, pos_insert)\n\n thumb.save(out_fname)\n # Use optipng to perform lossless compression on the resized image if\n # software is installed\n if os.environ.get('SKLEARN_DOC_OPTIPNG', False):\n try:\n subprocess.call([\"optipng\", \"-quiet\", \"-o\", \"9\", out_fname])\n except Exception:\n warnings.warn('Install optipng to reduce the size of the \\\n generated images')", "response": "Scales an image with the same aspect ratio centered in an anonon_image with a given max_width and max_height."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef save_thumbnail(image_path, base_image_name, gallery_conf):\n first_image_file = image_path.format(1)\n thumb_dir = os.path.join(os.path.dirname(first_image_file), 'thumb')\n if not os.path.exists(thumb_dir):\n os.makedirs(thumb_dir)\n\n thumb_file = os.path.join(thumb_dir,\n 'sphx_glr_%s_thumb.png' % base_image_name)\n\n if os.path.exists(first_image_file):\n scale_image(first_image_file, thumb_file, 400, 280)\n elif not os.path.exists(thumb_file):\n # create something to replace the thumbnail\n default_thumb_file = os.path.join(glr_path_static(), 'no_image.png')\n default_thumb_file = gallery_conf.get(\"default_thumb_file\",\n default_thumb_file)\n scale_image(default_thumb_file, thumb_file, 200, 140)", "response": "Save the thumbnail image"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ngenerate the gallery reStructuredText for an example directory", "response": "def generate_dir_rst(src_dir, target_dir, gallery_conf, seen_backrefs):\n \"\"\"Generate the gallery reStructuredText for an example directory\"\"\"\n if not os.path.exists(os.path.join(src_dir, 'README.txt')):\n print(80 * '_')\n print('Example directory %s does not have a README.txt file' %\n src_dir)\n print('Skipping this directory')\n print(80 * '_')\n return \"\" # because string is an expected return type\n\n fhindex = open(os.path.join(src_dir, 'README.txt')).read()\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n sorted_listdir = [fname for fname in sorted(os.listdir(src_dir))\n if fname.endswith('.py')]\n entries_text = []\n for fname in sorted_listdir:\n amount_of_code = generate_file_rst(fname, target_dir, src_dir,\n gallery_conf)\n new_fname = os.path.join(src_dir, fname)\n intro = extract_intro(new_fname)\n write_backreferences(seen_backrefs, gallery_conf,\n target_dir, fname, intro)\n this_entry = _thumbnail_div(target_dir, fname, intro) + \"\"\"\n\n.. toctree::\n :hidden:\n\n /%s/%s\\n\"\"\" % (target_dir, fname[:-3])\n entries_text.append((amount_of_code, this_entry))\n\n # sort to have the smallest entries in the beginning\n entries_text.sort()\n\n for _, entry_text in entries_text:\n fhindex += entry_text\n\n # clear at the end of the section\n fhindex += \"\"\".. raw:: html\\n\n \\n\\n\"\"\"\n\n return fhindex"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef execute_script(code_block, example_globals, image_path, fig_count,\n src_file, gallery_conf):\n \"\"\"Executes the code block of the example file\"\"\"\n time_elapsed = 0\n stdout = ''\n\n # We need to execute the code\n print('plotting code blocks in %s' % src_file)\n\n plt.close('all')\n cwd = os.getcwd()\n # Redirect output to stdout and\n orig_stdout = sys.stdout\n\n try:\n # First cd in the original example dir, so that any file\n # created by the example get created in this directory\n os.chdir(os.path.dirname(src_file))\n my_buffer = StringIO()\n my_stdout = Tee(sys.stdout, my_buffer)\n sys.stdout = my_stdout\n\n t_start = time()\n exec(code_block, example_globals)\n time_elapsed = time() - t_start\n\n sys.stdout = orig_stdout\n\n my_stdout = my_buffer.getvalue().strip().expandtabs()\n if my_stdout:\n stdout = CODE_OUTPUT.format(indent(my_stdout, ' ' * 4))\n os.chdir(cwd)\n figure_list = save_figures(image_path, fig_count, gallery_conf)\n\n # Depending on whether we have one or more figures, we're using a\n # horizontal list or a single rst call to 'image'.\n image_list = \"\"\n if len(figure_list) == 1:\n figure_name = figure_list[0]\n image_list = SINGLE_IMAGE % figure_name.lstrip('/')\n elif len(figure_list) > 1:\n image_list = HLIST_HEADER\n for figure_name in figure_list:\n image_list += HLIST_IMAGE_TEMPLATE % figure_name.lstrip('/')\n\n except Exception:\n formatted_exception = traceback.format_exc()\n\n print(80 * '_')\n print('%s is not compiling:' % src_file)\n print(formatted_exception)\n print(80 * '_')\n\n figure_list = []\n image_list = codestr2rst(formatted_exception, lang='pytb')\n\n # Overrides the output thumbnail in the gallery for easy identification\n broken_img = os.path.join(glr_path_static(), 'broken_example.png')\n shutil.copyfile(broken_img, os.path.join(cwd, image_path.format(1)))\n fig_count += 1 # raise count to avoid overwriting image\n\n # Breaks build on first example error\n\n if gallery_conf['abort_on_example_error']:\n raise\n\n finally:\n os.chdir(cwd)\n sys.stdout = orig_stdout\n\n print(\" - time elapsed : %.2g sec\" % time_elapsed)\n code_output = \"\\n{0}\\n\\n{1}\\n\\n\".format(image_list, stdout)\n\n return code_output, time_elapsed, fig_count + len(figure_list)", "response": "Executes the code block of the example file and returns a dictionary of the result."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ngenerates the rst file for a given example.", "response": "def generate_file_rst(fname, target_dir, src_dir, gallery_conf):\n \"\"\" Generate the rst file for a given example.\n\n Returns the amout of code (in characters) of the corresponding\n files.\n \"\"\"\n\n src_file = os.path.join(src_dir, fname)\n example_file = os.path.join(target_dir, fname)\n shutil.copyfile(src_file, example_file)\n\n image_dir = os.path.join(target_dir, 'images')\n if not os.path.exists(image_dir):\n os.makedirs(image_dir)\n\n base_image_name = os.path.splitext(fname)[0]\n image_fname = 'sphx_glr_' + base_image_name + '_{0:03}.png'\n image_path = os.path.join(image_dir, image_fname)\n\n script_blocks = split_code_and_text_blocks(example_file)\n\n amount_of_code = sum([len(bcontent)\n for blabel, bcontent in script_blocks\n if blabel == 'code'])\n\n if _plots_are_current(example_file, image_path):\n return amount_of_code\n\n time_elapsed = 0\n\n ref_fname = example_file.replace(os.path.sep, '_')\n example_rst = \"\"\"\\n\\n.. _sphx_glr_{0}:\\n\\n\"\"\".format(ref_fname)\n example_nb = Notebook(fname, target_dir)\n\n filename_pattern = gallery_conf.get('filename_pattern')\n if re.search(filename_pattern, src_file) and gallery_conf['plot_gallery']:\n # A lot of examples contains 'print(__doc__)' for example in\n # scikit-learn so that running the example prints some useful\n # information. Because the docstring has been separated from\n # the code blocks in sphinx-gallery, __doc__ is actually\n # __builtin__.__doc__ in the execution context and we do not\n # want to print it\n example_globals = {'__doc__': ''}\n fig_count = 0\n # A simple example has two blocks: one for the\n # example introduction/explanation and one for the code\n is_example_notebook_like = len(script_blocks) > 2\n for blabel, bcontent in script_blocks:\n if blabel == 'code':\n code_output, rtime, fig_count = execute_script(bcontent,\n example_globals,\n image_path,\n fig_count,\n src_file,\n gallery_conf)\n\n time_elapsed += rtime\n example_nb.add_code_cell(bcontent)\n\n if is_example_notebook_like:\n example_rst += codestr2rst(bcontent) + '\\n'\n example_rst += code_output\n else:\n example_rst += code_output\n example_rst += codestr2rst(bcontent) + '\\n'\n\n else:\n example_rst += text2string(bcontent) + '\\n'\n example_nb.add_markdown_cell(text2string(bcontent))\n else:\n for blabel, bcontent in script_blocks:\n if blabel == 'code':\n example_rst += codestr2rst(bcontent) + '\\n'\n example_nb.add_code_cell(bcontent)\n else:\n example_rst += bcontent + '\\n'\n example_nb.add_markdown_cell(text2string(bcontent))\n\n save_thumbnail(image_path, base_image_name, gallery_conf)\n\n time_m, time_s = divmod(time_elapsed, 60)\n example_nb.save_file()\n with open(os.path.join(target_dir, base_image_name + '.rst'), 'w') as f:\n example_rst += CODE_DOWNLOAD.format(time_m, time_s, fname,\n example_nb.file_name)\n f.write(example_rst)\n\n return amount_of_code"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _arburg2(X, order):\n x = np.array(X)\n N = len(x)\n\n if order <= 0.:\n raise ValueError(\"order must be > 0\")\n\n # Initialisation\n # ------ rho, den\n rho = sum(abs(x)**2.) / N # Eq 8.21 [Marple]_\n den = rho * 2. * N\n\n # ------ backward and forward errors\n ef = np.zeros(N, dtype=complex)\n eb = np.zeros(N, dtype=complex)\n for j in range(0, N): #eq 8.11\n ef[j] = x[j]\n eb[j] = x[j]\n\n # AR order to be stored\n a = np.zeros(1, dtype=complex)\n a[0] = 1\n # ---- rflection coeff to be stored\n ref = np.zeros(order, dtype=complex)\n\n temp = 1.\n E = np.zeros(order+1)\n E[0] = rho\n\n for m in range(0, order):\n #print m\n # Calculate the next order reflection (parcor) coefficient\n efp = ef[1:]\n ebp = eb[0:-1]\n #print efp, ebp\n num = -2.* np.dot(ebp.conj().transpose(), efp)\n den = np.dot(efp.conj().transpose(), efp)\n den += np.dot(ebp, ebp.conj().transpose())\n ref[m] = num / den\n\n # Update the forward and backward prediction errors\n ef = efp + ref[m] * ebp\n eb = ebp + ref[m].conj().transpose() * efp\n\n # Update the AR coeff.\n a.resize(len(a)+1)\n a = a + ref[m] * np.flipud(a).conjugate()\n\n # Update the prediction error\n E[m+1] = (1 - ref[m].conj().transpose()*ref[m]) * E[m]\n #print 'REF', ref, num, den\n return a, E[-1], ref", "response": "This version is 10 times faster than arburg but the output rho is not correct."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef arburg(X, order, criteria=None):\n if order <= 0.:\n raise ValueError(\"order must be > 0\")\n\n if order > len(X):\n raise ValueError(\"order must be less than length input - 2\")\n\n x = np.array(X)\n N = len(x)\n\n # Initialisation\n # ------ rho, den\n rho = sum(abs(x)**2.) / float(N) # Eq 8.21 [Marple]_\n den = rho * 2. * N\n\n # ---- criteria\n if criteria:\n from spectrum import Criteria\n crit = Criteria(name=criteria, N=N)\n crit.data = rho\n logging.debug('Step {}. old criteria={} new one={}. rho={}'.format(\n 0, crit.old_data, crit.data, rho))\n\n #p =0\n a = np.zeros(0, dtype=complex)\n ref = np.zeros(0, dtype=complex)\n ef = x.astype(complex)\n eb = x.astype(complex)\n temp = 1.\n # Main recursion\n\n for k in range(0, order):\n\n # calculate the next order reflection coefficient Eq 8.14 Marple\n num = sum([ef[j]*eb[j-1].conjugate() for j in range(k+1, N)])\n den = temp * den - abs(ef[k])**2 - abs(eb[N-1])**2\n kp = -2. * num / den #eq 8.14\n\n temp = 1. - abs(kp)**2.\n new_rho = temp * rho\n\n if criteria:\n logging.debug('Step {}. old criteria={} new one={}. rho={}'.format(\n k+1, crit.old_data, crit.data, new_rho))\n #k+1 because order goes from 1 to P whereas k starts at 0.\n status = crit(rho=temp*rho, k=k+1)\n if status is False:\n logging.debug('Stop criteria reached %s %s ' % (crit.data, crit.old_data))\n break\n # this should be after the criteria\n rho = new_rho\n if rho <= 0:\n raise ValueError(\"Found a negative value (expected positive stricly) %s. Decrease the order\" % rho)\n\n a.resize(a.size+1)\n a[k] = kp\n if k == 0:\n for j in range(N-1, k, -1):\n save2 = ef[j]\n ef[j] = save2 + kp * eb[j-1] # Eq. (8.7)\n eb[j] = eb[j-1] + kp.conjugate() * save2\n\n else:\n # update the AR coeff\n khalf = (k+1)//2 # FIXME here khalf must be an integer\n for j in range(0, khalf):\n ap = a[j] # previous value\n a[j] = ap + kp * a[k-j-1].conjugate() # Eq. (8.2)\n if j != k-j-1:\n a[k-j-1] = a[k-j-1] + kp * ap.conjugate() # Eq. (8.2)\n\n # update the prediction error\n for j in range(N-1, k, -1):\n save2 = ef[j]\n ef[j] = save2 + kp * eb[j-1] # Eq. (8.7)\n eb[j] = eb[j-1] + kp.conjugate() * save2\n\n # save the reflection coefficient\n ref.resize(ref.size+1)\n ref[k] = kp\n\n return a, rho, ref", "response": "r Estimates the complex autoregressive parameters by the Burg algorithm."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _numpy_cholesky(A, B):\n L = numpy.linalg.cholesky(A)\n # A=L*numpy.transpose(L).conjugate()\n # Ly = b\n y = numpy.linalg.solve(L,B)\n # Ux = y\n x = numpy.linalg.solve(L.transpose().conjugate(),y)\n return x, L", "response": "Solve Ax = B using numpy cholesky solver"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _numpy_solver(A, B):\n x = numpy.linalg.solve(A, B)\n return x", "response": "This function solve Ax = B directly without taking care of the input\n matrix properties."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef CHOLESKY(A, B, method='scipy'):\n if method == 'numpy_solver':\n X = _numpy_solver(A,B)\n return X\n elif method == 'numpy':\n X, _L = _numpy_cholesky(A, B)\n return X\n elif method == 'scipy':\n import scipy.linalg\n L = scipy.linalg.cholesky(A)\n X = scipy.linalg.cho_solve((L, False), B)\n else:\n raise ValueError('method must be numpy_solver, numpy_cholesky or cholesky_inplace')\n return X", "response": "Solve linear system Ax = B using CHOLESKY method."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef music(X, IP, NSIG=None, NFFT=default_NFFT, threshold=None, criteria='aic',\n verbose=False):\n \"\"\"Eigen value pseudo spectrum estimate. See :func:`eigenfre`\"\"\"\n return eigen(X, IP, NSIG=NSIG, method='music', NFFT=NFFT,\n threshold=threshold, criteria=criteria, verbose=verbose)", "response": "Eigen value pseudo spectrum estimate. See eigenenfre."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef eigen(X, P, NSIG=None, method='music', threshold=None, NFFT=default_NFFT,\n criteria='aic', verbose=False):\n r\"\"\"Pseudo spectrum using eigenvector method (EV or Music)\n\n This function computes either the Music or EigenValue (EV) noise\n subspace frequency estimator.\n\n First, an autocorrelation matrix of order `P` is computed from\n the data. Second, this matrix is separated into vector subspaces,\n one a signal subspace and the other a noise\n subspace using a SVD method to obtain the eigen values and vectors.\n From the eigen values :math:`\\lambda_i`, and eigen vectors :math:`v_k`,\n the **pseudo spectrum** (see note below) is computed as follows:\n\n .. math:: P_{ev}(f) = \\frac{1}{e^H(f)\\left(\\sum\\limits_{k=M+1}^{p} \\frac{1}{\\lambda_k}v_kv_k^H\\right)e(f)}\n\n The separation of the noise and signal subspaces requires expertise\n of the signal. However, AIC and MDL criteria may be used to automatically\n perform this task.\n\n You still need to provide the parameter `P` to indicate the maximum number\n of eigen values to be computed. The criteria will just select a subset\n to estimate the pseudo spectrum (see :func:`~spectrum.criteria.aic_eigen`\n and :func:`~spectrum.criteria.mdl_eigen` for details.\n\n .. note:: **pseudo spectrum**. func:`eigen` does not compute a PSD estimate.\n Indeed, the method does not preserve the measured process power.\n\n :param X: Array data samples\n :param int P: maximum number of eigen values to compute. NSIG (if\n specified) must therefore be less than P.\n :param str method: 'music' or 'ev'.\n :param int NSIG: If specified, the signal sub space uses NSIG eigen values.\n :param float threshold: If specified, the signal sub space is made of the\n eigen values larger than :math:`\\rm{threshold} \\times \\lambda_{min}`,\n where :math:`\\lambda_{min}` is the minimum eigen values.\n :param int NFFT: total length of the final data sets (padded with zero \n if needed; default is 4096)\n\n :return:\n * PSD: Array of real frequency estimator values (two sided for\n complex data and one sided for real data)\n * S, the eigen values\n\n .. plot::\n :width: 80%\n :include-source:\n\n from spectrum import eigen, marple_data\n from pylab import plot, log10, linspace, legend, axis\n\n psd, ev = eigen(marple_data, 15, NSIG=11)\n f = linspace(-0.5, 0.5, len(psd))\n plot(f, 10 * log10(psd/max(psd)), label='User defined')\n\n psd, ev = eigen(marple_data, 15, threshold=2)\n plot(f, 10 * log10(psd/max(psd)), label='threshold method (100)')\n\n psd, ev = eigen(marple_data, 15)\n plot(f, 10 * log10(psd/max(psd)), label='AIC method (8)')\n\n legend()\n axis([-0.5, 0.5, -120, 0])\n\n .. seealso::\n :func:`pev`,\n :func:`pmusic`,\n :func:`~spectrum.criteria.aic_eigen`\n\n :References: [Marple]_, Chap 13\n\n .. todo:: for developers:\n\n * what should be the second argument of the criteria N, N-P, P...?\n * what should be the max value of NP\n \"\"\"\n if method not in ['music', 'ev']:\n raise ValueError(\"method must be 'music' or 'ev'\")\n\n if NSIG != None and threshold != None:\n raise ValueError(\"NSIG and threshold cannot be provided together\")\n\n if NSIG is not None:\n if NSIG < 0:\n raise ValueError('NSIG must be positive')\n if NSIG >= P:\n raise ValueError(\"NSIG must be stricly less than IP\")\n\n #\n N = len(X)\n NP = N - P\n\n assert 2 * NP > P-1, 'decrease the second argument'\n if NP > 100:\n NP = 100\n\n FB = np.zeros((2*NP, P), dtype=complex)\n #FB = numpy.zeros((MAXU, IP), dtype=complex)\n Z = np.zeros(NFFT, dtype=complex)\n PSD = np.zeros(NFFT)\n\n # These loops can surely be replaced by a function that create such matrix\n for I in range(0, NP):\n for K in range(0, P):\n FB[I, K] = X[I-K+P-1]\n FB[I+NP, K] = X[I+K+1].conjugate()\n\n # This commented line produces the correct FB, as the 2 for loops above\n # It is more elegant but slower...corrmtx needs to be optimised (20/4/11)\n #FB2 = spectrum.linalg.corrmtx(X, P-1, method='modified')\n\n #Compute the eigen values / vectors\n _U, S, V = svd (FB)\n # U and V are not the same as in Marple. Real or Imaginary absolute values\n # are correct but signs are not. This is wierd because the svd function\n # gives the same result as cvsd in Marple. Is FB correct ? it seems so.\n # The following operation has to be done. Otherwise, the resulting PSD is\n # not corect\n V = -V.transpose()\n\n NSIG = _get_signal_space(S, 2*NP,\n verbose=verbose, threshold=threshold,\n NSIG=NSIG, criteria=criteria)\n\n #C AI or Expert Knowledge to choose \"signal\" singular values, or input\n #C NSIG at this point\n for I in range(NSIG, P):\n Z[0:P] = V[0:P, I]\n Z[P:NFFT] = 0\n\n Z = fft(Z, NFFT)\n\n if method == 'music':\n PSD = PSD + abs(Z)**2.\n elif method == 'ev' :\n PSD = PSD + abs(Z)**2. / S[I]\n\n PSD = 1./PSD\n\n # for some reasons, we need to rearrange the output. this is related to\n # the way U and V are order in the routine svd\n nby2 = int(NFFT/2)\n\n #return PSD, S\n\n newpsd = np.append(PSD[nby2:0:-1], PSD[nby2*2-1:nby2-1:-1])\n return newpsd, S", "response": "r Computes the pseudo spectrum of the specified method using the specified number of eigen values."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngetting the signal space from the signal vector S and NP", "response": "def _get_signal_space(S, NP, verbose=False, threshold=None, NSIG=None,\n criteria='aic'):\n \"\"\"todo\n\n\n \"\"\"\n from .criteria import aic_eigen, mdl_eigen\n # This section selects automatically the noise and signal subspaces.\n # NSIG being the number of eigenvalues corresponding to signals.\n if NSIG is None:\n if threshold is None:\n logging.debug('computing NSIG using AIC method')\n # get the minimum index of the AIC vector\n if criteria == 'aic':\n aic = aic_eigen(S, NP*2)\n elif criteria == 'mdl':\n aic = mdl_eigen(S, NP*2)\n # get the minimum index of the AIC vector, add 1 to get the NSIG\n NSIG = np.argmin(aic) + 1\n logging.debug('NSIG=', NSIG, ' found as the number of pertinent sinusoids')\n else:\n logging.debug('computing NSIG using user threshold ')\n # following an idea from Matlab, pmusic, we look at the minimum\n # eigen value, and split the eigen values above and below\n # K times min eigen value, where K is >1\n m = threshold * min(S)\n new_s = S[np.where(S>m)]\n NSIG = len(new_s)\n logging.debug('found', NSIG)\n if NSIG == 0:\n NSIG = 1\n return NSIG"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef speriodogram(x, NFFT=None, detrend=True, sampling=1.,\n scale_by_freq=True, window='hamming', axis=0):\n \"\"\"Simple periodogram, but matrices accepted.\n\n :param x: an array or matrix of data samples.\n :param NFFT: length of the data before FFT is computed (zero padding)\n :param bool detrend: detrend the data before co,puteing the FFT\n :param float sampling: sampling frequency of the input :attr:`data`.\n\n :param scale_by_freq:\n :param str window:\n\n :return: 2-sided PSD if complex data, 1-sided if real.\n\n if a matrix is provided (using numpy.matrix), then a periodogram\n is computed for each row. The returned matrix has the same shape as the input\n matrix.\n\n The mean of the input data is also removed from the data before computing\n the psd.\n\n .. plot::\n :width: 80%\n :include-source:\n\n from pylab import grid, semilogy\n from spectrum import data_cosine, speriodogram\n data = data_cosine(N=1024, A=0.1, sampling=1024, freq=200)\n semilogy(speriodogram(data, detrend=False, sampling=1024), marker='o')\n grid(True)\n\n\n .. plot::\n :width: 80%\n :include-source:\n\n import numpy\n from spectrum import speriodogram, data_cosine\n from pylab import figure, semilogy, figure ,imshow\n # create N data sets and make the frequency dependent on the time\n N = 100\n m = numpy.concatenate([data_cosine(N=1024, A=0.1, sampling=1024, freq=x) \n for x in range(1, N)]);\n m.resize(N, 1024)\n res = speriodogram(m)\n figure(1)\n semilogy(res)\n figure(2)\n imshow(res.transpose(), aspect='auto')\n\n .. todo:: a proper spectrogram class/function that takes care of normalisation\n \"\"\"\n x = np.array(x)\n # array with 1 dimension case\n if x.ndim == 1:\n axis = 0\n r = x.shape[0]\n w = Window(r, window) #same size as input data\n w = w.data\n # matrix case\n elif x.ndim == 2:\n logging.debug('2D array. each row is a 1D array')\n [r, c] = x.shape\n w = np.array([Window(r, window).data for this in range(c)]).reshape(r,c) \n\n if NFFT is None:\n NFFT = len(x)\n\n isreal = np.isrealobj(x)\n\n if detrend == True:\n m = np.mean(x, axis=axis)\n else:\n m = 0\n\n if isreal == True:\n if x.ndim == 2:\n res = (abs (rfft (x*w - m, NFFT, axis=0))) ** 2. / r\n else:\n res = (abs (rfft (x*w - m, NFFT, axis=-1))) ** 2. / r\n else:\n if x.ndim == 2:\n res = (abs (fft (x*w - m, NFFT, axis=0))) ** 2. / r\n else:\n res = (abs (fft (x*w - m, NFFT, axis=-1))) ** 2. / r\n\n if scale_by_freq is True:\n df = sampling / float(NFFT)\n res*= 2 * np.pi / df\n\n if x.ndim == 1:\n return res.transpose()\n else:\n return res", "response": "Simple periodogram but matrices accepted."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef WelchPeriodogram(data, NFFT=None, sampling=1., **kargs):\n from pylab import psd\n spectrum = Spectrum(data, sampling=1.)\n\n P = psd(data, NFFT, Fs=sampling, **kargs)\n spectrum.psd = P[0]\n #spectrum.__Spectrum_sides = 'twosided'\n\n return P, spectrum", "response": "r This function returns a simple periodogram wrapper of numpy. psd function that calculates the periodogram of the data."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef DaniellPeriodogram(data, P, NFFT=None, detrend='mean', sampling=1.,\n scale_by_freq=True, window='hamming'):\n r\"\"\"Return Daniell's periodogram.\n\n To reduce fast fluctuations of the spectrum one idea proposed by daniell\n is to average each value with points in its neighboorhood. It's like\n a low filter.\n\n .. math:: \\hat{P}_D[f_i]= \\frac{1}{2P+1} \\sum_{n=i-P}^{i+P} \\tilde{P}_{xx}[f_n]\n\n where P is the number of points to average.\n\n Daniell's periodogram is the convolution of the spectrum with a low filter:\n\n .. math:: \\hat{P}_D(f)= \\hat{P}_{xx}(f)*H(f)\n\n Example::\n\n >>> DaniellPeriodogram(data, 8)\n\n if N/P is not integer, the final values of the original PSD are not used.\n\n using DaniellPeriodogram(data, 0) should give the original PSD.\n\n \"\"\"\n psd = speriodogram(data, NFFT=NFFT, detrend=detrend, sampling=sampling,\n scale_by_freq=scale_by_freq, window=window)\n\n if len(psd) % 2 == 1:\n datatype = 'real'\n else:\n datatype = 'complex'\n\n N = len(psd)\n _slice = 2 * P + 1\n if datatype == 'real': #must get odd value\n newN = np.ceil(psd.size/float(_slice))\n if newN % 2 == 0:\n newN = psd.size/_slice\n else:\n newN = np.ceil(psd.size/float(_slice))\n if newN % 2 == 1:\n newN = psd.size/_slice\n\n newpsd = np.zeros(int(newN)) # keep integer division\n for i in range(0, newpsd.size):\n count = 0 #needed to know the number of valid averaged values\n for n in range(i*_slice-P, i*_slice+P+1): #+1 to have P values on each sides\n if n > 0 and n>> print(list(Range(8).centerdc_gen()))\n [-0.5, -0.375, -0.25, -0.125, 0.0, 0.125, 0.25, 0.375]\n\n \"\"\"\n for a in range(0, self.N):\n yield (a-self.N/2) * self.df"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn the one - sided frequency range as a generator.", "response": "def onesided_gen(self):\n \"\"\"Return the one-sided frequency range as a generator.\n\n If :attr:`N` is even, the length is N/2 + 1.\n If :attr:`N` is odd, the length is (N+1)/2.\n\n ::\n\n >>> print(list(Range(8).onesided()))\n [0.0, 0.125, 0.25, 0.375, 0.5]\n >>> print(list(Range(9).onesided()))\n [0.0, 0.1111, 0.2222, 0.3333, 0.4444]\n\n \"\"\"\n if self.N % 2 == 0:\n for n in range(0, self.N//2 + 1):\n yield n * self.df\n else:\n for n in range(0, (self.N+1)//2):\n yield n * self.df"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the frequency vector according to the given sides.", "response": "def frequencies(self, sides=None):\n\n \"\"\"Return the frequency vector according to :attr:`sides`\"\"\"\n # use the attribute sides except if a valid sides argument is provided\n if sides is None:\n sides = self.sides\n if sides not in self._sides_choices:\n raise errors.SpectrumChoiceError(sides, self._sides_choices)\n\n if sides == 'onesided':\n return self._range.onesided()\n if sides == 'twosided':\n return self._range.twosided()\n if sides == 'centerdc':\n return self._range.centerdc()"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_converted_psd(self, sides):\n if sides == self.sides:\n #nothing to be done is sides = :attr:`sides\n return self.__psd\n\n if self.datatype == 'complex':\n assert sides != 'onesided', \\\n \"complex datatype so sides cannot be onesided.\"\n\n if self.sides == 'onesided':\n logging.debug('Current sides is onesided')\n if sides == 'twosided':\n logging.debug('--->Converting to twosided')\n # here we divide everything by 2 to get the twosided version\n #N = self.NFFT\n newpsd = numpy.concatenate((self.psd[0:-1]/2., list(reversed(self.psd[0:-1]/2.))))\n # so we need to multiply by 2 the 0 and FS/2 frequencies\n newpsd[-1] = self.psd[-1]\n newpsd[0] *= 2.\n elif sides == 'centerdc':\n # FIXME. this assumes data is even so PSD is stored as\n # P0 X1 X2 X3 P1\n logging.debug('--->Converting to centerdc')\n P0 = self.psd[0]\n P1 = self.psd[-1]\n newpsd = numpy.concatenate((self.psd[-1:0:-1]/2., self.psd[0:-1]/2.))\n # so we need to multiply by 2 the 0 and F2/2 frequencies\n #newpsd[-1] = P0 / 2\n newpsd[0] = P1\n elif self.sides == 'twosided':\n logging.debug('Current sides is twosided')\n if sides == 'onesided':\n # we assume that data is stored as X0,X1,X2,X3,XN\n # that is original data is even.\n logging.debug('Converting to onesided assuming ori data is even')\n midN = (len(self.psd)-2) / 2\n newpsd = numpy.array(self.psd[0:int(midN)+2]*2)\n newpsd[0] /= 2\n newpsd[-1] = self.psd[-1]\n elif sides == 'centerdc':\n newpsd = stools.twosided_2_centerdc(self.psd)\n elif self.sides == 'centerdc': # same as twosided to onesided\n logging.debug('Current sides is centerdc')\n if sides == 'onesided':\n logging.debug('--->Converting to onesided')\n midN = int(len(self.psd) / 2)\n P1 = self.psd[0]\n newpsd = numpy.append(self.psd[midN:]*2, P1)\n elif sides == 'twosided':\n newpsd = stools.centerdc_2_twosided(self.psd)\n else:\n raise ValueError(\"sides must be set to 'onesided', 'twosided' or 'centerdc'\")\n\n return newpsd", "response": "This function returns the PSD in the given sides format in the onesided twosided or centerdc format."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef plot(self, filename=None, norm=False, ylim=None,\n sides=None, **kargs):\n \"\"\"a simple plotting routine to plot the PSD versus frequency.\n\n :param str filename: save the figure into a file\n :param norm: False by default. If True, the PSD is normalised.\n :param ylim: readjust the y range .\n :param sides: if not provided, :attr:`sides` is used. See :attr:`sides`\n for details.\n :param kargs: any optional argument accepted by :func:`pylab.plot`.\n\n .. plot::\n :width: 80%\n :include-source:\n\n from spectrum import *\n p = Periodogram(marple_data)\n p.plot(norm=True, marker='o')\n\n \"\"\"\n import pylab\n from pylab import ylim as plt_ylim\n #First, check that psd attribute is up-to-date\n # just to get the PSD to be recomputed if needed\n _ = self.psd\n\n\n # check that the input sides parameter is correct if provided\n if sides is not None:\n if sides not in self._sides_choices:\n raise errors.SpectrumChoiceError(sides, self._sides_choices)\n\n # if sides is provided but identical to the current psd, nothing to do.\n # if sides not provided, let us use self.sides\n if sides is None or sides == self.sides:\n frequencies = self.frequencies()\n psd = self.psd\n sides = self.sides\n elif sides is not None:\n # if sides argument is different from the attribute, we need to\n # create a new PSD/Freq ; indeed we do not want to change the\n # attribute itself\n\n # if data is complex, one-sided is wrong in any case.\n if self.datatype == 'complex':\n if sides == 'onesided':\n raise ValueError(\"sides cannot be one-sided with complex data\")\n\n logging.debug(\"sides is different from the one provided. Converting PSD\")\n frequencies = self.frequencies(sides=sides)\n psd = self.get_converted_psd(sides)\n\n if len(psd) != len(frequencies):\n raise ValueError(\"PSD length is %s and freq length is %s\" % (len(psd), len(frequencies)))\n\n if 'ax' in list(kargs.keys()):\n save_ax = pylab.gca()\n pylab.sca(kargs['ax'])\n rollback = True\n del kargs['ax']\n else:\n rollback = False\n\n if norm:\n pylab.plot(frequencies, 10 * stools.log10(psd/max(psd)), **kargs)\n else:\n pylab.plot(frequencies, 10 * stools.log10(psd),**kargs)\n\n pylab.xlabel('Frequency')\n pylab.ylabel('Power (dB)')\n pylab.grid(True)\n\n if ylim:\n plt_ylim(ylim)\n\n if sides == 'onesided':\n pylab.xlim(0, self.sampling/2.)\n elif sides == 'twosided':\n pylab.xlim(0, self.sampling)\n elif sides == 'centerdc':\n pylab.xlim(-self.sampling/2., self.sampling/2.)\n\n if filename:\n pylab.savefig(filename)\n\n if rollback:\n pylab.sca(save_ax)\n\n del psd, frequencies", "response": "a simple plotting routine to plot the PSD versus frequency."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef ipy_notebook_skeleton():\n py_version = sys.version_info\n notebook_skeleton = {\n \"cells\": [],\n \"metadata\": {\n \"kernelspec\": {\n \"display_name\": \"Python \" + str(py_version[0]),\n \"language\": \"python\",\n \"name\": \"python\" + str(py_version[0])\n },\n \"language_info\": {\n \"codemirror_mode\": {\n \"name\": \"ipython\",\n \"version\": py_version[0]\n },\n \"file_extension\": \".py\",\n \"mimetype\": \"text/x-python\",\n \"name\": \"python\",\n \"nbconvert_exporter\": \"python\",\n \"pygments_lexer\": \"ipython\" + str(py_version[0]),\n \"version\": '{0}.{1}.{2}'.format(*sys.version_info[:3])\n }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 0\n }\n return notebook_skeleton", "response": "Returns a dictionary with the elements of a Jupyter notebook that are in IPython notebook format."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef rst2md(text):\n\n top_heading = re.compile(r'^=+$\\s^([\\w\\s-]+)^=+$', flags=re.M)\n text = re.sub(top_heading, r'# \\1', text)\n\n math_eq = re.compile(r'^\\.\\. math::((?:.+)?(?:\\n+^ .+)*)', flags=re.M)\n text = re.sub(math_eq,\n lambda match: r'$${0}$$'.format(match.group(1).strip()),\n text)\n inline_math = re.compile(r':math:`(.+)`')\n text = re.sub(inline_math, r'$\\1$', text)\n\n return text", "response": "Converts the RST text from the examples docstrigs and comments\n into markdown text for IPython Notebooks"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef add_markdown_cell(self, text):\n markdown_cell = {\n \"cell_type\": \"markdown\",\n \"metadata\": {},\n \"source\": [rst2md(text)]\n }\n self.work_notebook[\"cells\"].append(markdown_cell)", "response": "Add a markdown cell to the notebook"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nsave the notebook to a file", "response": "def save_file(self):\n \"\"\"Saves the notebook to a file\"\"\"\n with open(self.write_file, 'w') as out_nb:\n json.dump(self.work_notebook, out_nb, indent=2)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef arma2psd(A=None, B=None, rho=1., T=1., NFFT=4096, sides='default',\n norm=False):\n r\"\"\"Computes power spectral density given ARMA values.\n\n This function computes the power spectral density values\n given the ARMA parameters of an ARMA model. It assumes that\n the driving sequence is a white noise process of zero mean and\n variance :math:`\\rho_w`. The sampling frequency and noise variance are\n used to scale the PSD output, which length is set by the user with the\n `NFFT` parameter.\n\n :param array A: Array of AR parameters (complex or real)\n :param array B: Array of MA parameters (complex or real)\n :param float rho: White noise variance to scale the returned PSD\n :param float T: Sample interval in seconds to scale the returned PSD\n :param int NFFT: Final size of the PSD\n :param str sides: Default PSD is two-sided, but sides can be set to centerdc.\n\n .. warning:: By convention, the AR or MA arrays does not contain the\n A0=1 value.\n\n If :attr:`B` is None, the model is a pure AR model. If :attr:`A` is None,\n the model is a pure MA model.\n\n :return: two-sided PSD\n\n .. rubric:: Details:\n\n AR case: the power spectral density is:\n\n .. math:: P_{ARMA}(f) = T \\rho_w \\left|\\frac{B(f)}{A(f)}\\right|^2\n\n where:\n\n .. math:: A(f) = 1 + \\sum_{k=1}^q b(k) e^{-j2\\pi fkT}\n .. math:: B(f) = 1 + \\sum_{k=1}^p a(k) e^{-j2\\pi fkT}\n\n .. rubric:: **Example:**\n\n .. plot::\n :width: 80%\n :include-source:\n\n import spectrum.arma\n from pylab import plot, log10, legend\n plot(10*log10(spectrum.arma.arma2psd([1,0.5],[0.5,0.5])), label='ARMA(2,2)')\n plot(10*log10(spectrum.arma.arma2psd([1,0.5],None)), label='AR(2)')\n plot(10*log10(spectrum.arma.arma2psd(None,[0.5,0.5])), label='MA(2)')\n legend()\n\n :References: [Marple]_\n \"\"\"\n if NFFT is None:\n NFFT = 4096\n\n if A is None and B is None:\n raise ValueError(\"Either AR or MA model must be provided\")\n\n psd = np.zeros(NFFT, dtype=complex)\n\n if A is not None:\n ip = len(A)\n den = np.zeros(NFFT, dtype=complex)\n den[0] = 1.+0j\n for k in range(0, ip):\n den[k+1] = A[k]\n denf = fft(den, NFFT)\n\n if B is not None:\n iq = len(B)\n num = np.zeros(NFFT, dtype=complex)\n num[0] = 1.+0j\n for k in range(0, iq):\n num[k+1] = B[k]\n numf = fft(num, NFFT)\n\n # Changed in version 0.6.9 (divided by T instead of multiply)\n if A is not None and B is not None:\n psd = rho / T * abs(numf)**2. / abs(denf)**2.\n elif A is not None:\n psd = rho / T / abs(denf)**2.\n elif B is not None:\n psd = rho / T * abs(numf)**2.\n\n\n psd = np.real(psd)\n # The PSD is a twosided PSD.\n # to obtain the centerdc\n if sides != 'default':\n from . import tools\n assert sides in ['centerdc']\n if sides == 'centerdc':\n psd = tools.twosided_2_centerdc(psd)\n\n if norm == True:\n psd /= max(psd)\n\n return psd", "response": "r Calculates the power spectral density of the given ARMA parameters."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef ma(X, Q, M):\n if Q <= 0 or Q >= M:\n raise ValueError('Q(MA) must be in ]0,lag[')\n\n #C Fit a high-order AR to the data\n a, rho, _c = yulewalker.aryule(X, M, 'biased') #! Eq. (10.5)\n\n #add an element unity to the AR parameter array\n a = np.insert(a, 0, 1)\n\n #C Find MA parameters from autocorrelations by Yule-Walker method\n ma_params, _p, _c = yulewalker.aryule(a, Q, 'biased') #! Eq. (10.7)\n\n return ma_params, rho", "response": "Moving average estimator.\n\n This program provides an estimate of the moving average parameters\n and driving noise variance for a data sequence based on a\n long AR model and a least squares fit.\n\n :param array X: The input data array\n :param int Q: Desired MA model order (must be >0 and = 0:\n key = dict_str[pos_last:pos]\n if dict_str[pos + 1] == '[':\n # value is a list\n pos_tmp = dict_str.find(']', pos + 1)\n if pos_tmp < 0:\n raise RuntimeError('error when parsing dict')\n value = dict_str[pos + 2: pos_tmp].split(',')\n # try to convert elements to int\n for i in range(len(value)):\n try:\n value[i] = int(value[i])\n except ValueError:\n pass\n elif dict_str[pos + 1] == '{':\n # value is another dictionary\n subdict_str = _select_block(dict_str[pos:], '{', '}')\n value = _parse_dict_recursive(subdict_str)\n pos_tmp = pos + len(subdict_str)\n else:\n raise ValueError('error when parsing dict: unknown elem')\n\n key = key.strip('\"')\n if len(key) > 0:\n dict_out[key] = value\n\n pos_last = dict_str.find(',', pos_tmp)\n if pos_last < 0:\n break\n pos_last += 1\n pos = dict_str.find(':', pos_last)\n\n return dict_out"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef parse_sphinx_searchindex(searchindex):\n # Make sure searchindex uses UTF-8 encoding\n if hasattr(searchindex, 'decode'):\n searchindex = searchindex.decode('UTF-8')\n\n # parse objects\n query = 'objects:'\n pos = searchindex.find(query)\n if pos < 0:\n raise ValueError('\"objects:\" not found in search index')\n\n sel = _select_block(searchindex[pos:], '{', '}')\n objects = _parse_dict_recursive(sel)\n\n # parse filenames\n query = 'filenames:'\n pos = searchindex.find(query)\n if pos < 0:\n raise ValueError('\"filenames:\" not found in search index')\n filenames = searchindex[pos + len(query) + 1:]\n filenames = filenames[:filenames.find(']')]\n filenames = [f.strip('\"') for f in filenames.split(',')]\n\n return filenames, objects", "response": "Parse a Sphinx search index and return a list of filenames and objects."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nembedding hyperlinks to documentation into example code", "response": "def embed_code_links(app, exception):\n \"\"\"Embed hyperlinks to documentation into example code\"\"\"\n if exception is not None:\n return\n\n # No need to waste time embedding hyperlinks when not running the examples\n # XXX: also at the time of writing this fixes make html-noplot\n # for some reason I don't fully understand\n if not app.builder.config.plot_gallery:\n return\n\n # XXX: Whitelist of builders for which it makes sense to embed\n # hyperlinks inside the example html. Note that the link embedding\n # require searchindex.js to exist for the links to the local doc\n # and there does not seem to be a good way of knowing which\n # builders creates a searchindex.js.\n if app.builder.name not in ['html', 'readthedocs']:\n return\n\n print('Embedding documentation hyperlinks in examples..')\n\n gallery_conf = app.config.sphinx_gallery_conf\n\n gallery_dirs = gallery_conf['gallery_dirs']\n if not isinstance(gallery_dirs, list):\n gallery_dirs = [gallery_dirs]\n\n for gallery_dir in gallery_dirs:\n _embed_code_links(app, gallery_conf, gallery_dir)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _get_link(self, cobj):\n\n fname_idx = None\n full_name = cobj['module_short'] + '.' + cobj['name']\n if full_name in self._searchindex['objects']:\n value = self._searchindex['objects'][full_name]\n if isinstance(value, dict):\n value = value[next(iter(value.keys()))]\n fname_idx = value[0]\n elif cobj['module_short'] in self._searchindex['objects']:\n value = self._searchindex['objects'][cobj['module_short']]\n if cobj['name'] in value.keys():\n fname_idx = value[cobj['name']][0]\n\n if fname_idx is not None:\n fname = self._searchindex['filenames'][fname_idx] + '.html'\n\n if self._is_windows:\n fname = fname.replace('/', '\\\\')\n link = os.path.join(self.doc_url, fname)\n else:\n link = posixpath.join(self.doc_url, fname)\n\n if hasattr(link, 'decode'):\n link = link.decode('utf-8', 'replace')\n\n if link in self._page_cache:\n html = self._page_cache[link]\n else:\n html = get_data(link, self.gallery_dir)\n self._page_cache[link] = html\n\n # test if cobj appears in page\n comb_names = [cobj['module_short'] + '.' + cobj['name']]\n if self.extra_modules_test is not None:\n for mod in self.extra_modules_test:\n comb_names.append(mod + '.' + cobj['name'])\n url = False\n if hasattr(html, 'decode'):\n # Decode bytes under Python 3\n html = html.decode('utf-8', 'replace')\n\n for comb_name in comb_names:\n if hasattr(comb_name, 'decode'):\n # Decode bytes under Python 3\n comb_name = comb_name.decode('utf-8', 'replace')\n if comb_name in html:\n url = link + u'#' + comb_name\n link = url\n else:\n link = False\n\n return link", "response": "Get a valid link for the object cobj."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef create_all_psd():\n\n f = pylab.linspace(0, 1, 4096)\n\n pylab.figure(figsize=(12,8))\n\n # MA model\n p = spectrum.pma(xx, 64,128); p(); p.plot()\n \"\"\"\n #ARMA 15 order\n a, b, rho = spectrum.arma_estimate(data, 15,15, 30)\n psd = spectrum.arma2psd(A=a,B=b, rho=rho)\n newpsd = tools.cshift(psd, len(psd)//2) # switch positive and negative freq\n pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='ARMA 15,15')\n \"\"\"\n # YULE WALKER\n p = spectrum.pyule(xx, 7 , NFFT=4096, scale_by_freq=False); p.plot()\n # equivalent to\n # plot([x for x in p.frequencies()] , 10*log10(p.psd)); grid(True)\n\n #burg method\n p = spectrum.pburg(xx, 7, scale_by_freq=False); p.plot()\n\n #pcovar\n p = spectrum.pcovar(xx, 7, scale_by_freq=False); p.plot()\n\n #pmodcovar\n p = spectrum.pmodcovar(xx, 7, scale_by_freq=False); p.plot()\n\n # correlogram\n p = spectrum.pcorrelogram(xx, lag=60, NFFT=512, scale_by_freq=False); p.plot()\n\n # minvar\n p = spectrum.pminvar(xx, 7, NFFT=256, scale_by_freq=False); p.plot()\n\n # pmusic\n p = spectrum.pmusic(xx, 10,4, scale_by_freq=False); p.plot()\n\n # pmusic\n p = spectrum.pev(xx, 10, 4, scale_by_freq=False); p.plot()\n\n # periodogram\n p = spectrum.Periodogram(xx, scale_by_freq=False); p.plot()\n\n #\n legend( [\"MA 32\", \"pyule 7\", \"pburg 7\", \"pcovar\", \"pmodcovar\", \"correlogram\",\n \"minvar\", \"pmusic\", \"pev\", \"periodgram\"])\n\n\n pylab.ylim([-80,80])", "response": "Create all the PSDs for all the data points."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef tf2zp(b,a):\n from numpy import roots\n assert len(b) == len(a), \"length of the vectors a and b must be identical. fill with zeros if needed.\"\n\n g = b[0] / a[0]\n z = roots(b)\n p = roots(a)\n\n return z, p, g", "response": "Convert a two - dimensional array of transfer function filter parameters to zero - pole - gain form."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngives two list or arrays pad with zeros the shortest array", "response": "def eqtflength(b,a):\n \"\"\"Given two list or arrays, pad with zeros the shortest array\n\n :param b: list or array\n :param a: list or array\n\n\n .. doctest::\n\n >>> from spectrum.transfer import eqtflength\n >>> a = [1,2]\n >>> b = [1,2,3,4]\n >>> a, b, = eqtflength(a,b)\n\n \"\"\"\n d = abs(len(b)-len(a))\n if d != 0:\n if len(a) > len(b):\n try:\n b.extend([0.]*d)\n except:\n b = np.append(b, [0]*d)\n elif len(b)>len(a):\n try:\n a.extend([0.]*d)\n except:\n a = np.append(a, [0]*d)\n return b,a\n else:\n return b,a"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nconvert a numerator polynomial to zero - pole - gain filter parameter form a numerator polynomial.", "response": "def tf2zpk(b, a):\n \"\"\"Return zero, pole, gain (z,p,k) representation from a numerator,\n denominator representation of a linear filter.\n\n Convert zero-pole-gain filter parameters to transfer function form\n\n :param ndarray b: numerator polynomial.\n :param ndarray a: numerator and denominator polynomials.\n\n :return:\n * z : ndarray Zeros of the transfer function.\n * p : ndarray Poles of the transfer function.\n * k : float System gain.\n\n If some values of b are too close to 0, they are removed. In that case, a\n BadCoefficients warning is emitted.\n\n .. doctest::\n\n >>> import scipy.signal\n >>> from spectrum.transfer import tf2zpk\n >>> [b, a] = scipy.signal.butter(3.,.4)\n >>> z, p ,k = tf2zpk(b,a)\n\n .. seealso:: :func:`zpk2tf`\n .. note:: wrapper of scipy function tf2zpk\n \"\"\"\n import scipy.signal\n z,p,k = scipy.signal.tf2zpk(b, a)\n return z,p,k"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef ss2zpk(a,b,c,d, input=0):\n import scipy.signal\n z, p, k = scipy.signal.ss2zpk(a, b, c, d, input=input)\n return z, p, k", "response": "State - space representation to zero - pole - gain representation."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef zpk2tf(z, p, k):\n import scipy.signal\n b, a = scipy.signal.zpk2tf(z, p, k)\n return b, a", "response": "r Return polynomial transfer function representation from zeros poles and gains of each numerator transfer function."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nzeroing - pole - gain representation to state - space representation", "response": "def zpk2ss(z, p, k):\n \"\"\"Zero-pole-gain representation to state-space representation\n\n :param sequence z,p: Zeros and poles.\n :param float k: System gain.\n\n :return:\n * A, B, C, D : ndarray State-space matrices.\n\n .. note:: wrapper of scipy function zpk2ss\n \"\"\"\n import scipy.signal\n return scipy.signal.zpk2ss(z,p,k)"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef create_window(N, name=None, **kargs):\n if name is None:\n name = 'rectangle'\n name = name.lower()\n assert name in list(window_names.keys()), \\\n \"\"\"window name %s not implemented or incorrect. Try to use one of %s\"\"\"\\\n % (name, window_names)\n\n\n # create the function name\n f = eval(window_names[name])\n\n windows_with_parameters = \\\n {'kaiser': {'beta': eval(window_names['kaiser']).__defaults__[0]},\n 'blackman': {'alpha': eval(window_names['blackman']).__defaults__[0]},\n 'cauchy': {'alpha': eval(window_names['cauchy']).__defaults__[0]},\n 'flattop': {'mode': eval(window_names['flattop']).__defaults__[0]},\n 'gaussian': {'alpha': eval(window_names['gaussian']).__defaults__[0]},\n 'chebwin': {'attenuation':eval(window_names['chebwin']).__defaults__[0]},\n 'tukey': {'r':eval(window_names['tukey']).__defaults__[0]},\n 'poisson': {'alpha': eval(window_names['poisson']).__defaults__[0]},\n 'poisson_hanning': {'alpha':\n eval(window_names['poisson_hanning']).__defaults__[0]},\n 'taylor': {'nbar': eval(window_names['taylor']).__defaults__[0],\n 'sll': eval(window_names['taylor']).__defaults__[0]}, \n }\n\n if name not in list(windows_with_parameters.keys()):\n if len(kargs) == 0:\n # no parameters, so we directly call the function\n w = f(N)\n else:\n raise ValueError(\"\"\"\n Parameters do not match any of the window. The window provided\n do not expect any parameters. Try to remove the parameters\"\"\")\n elif name in list(windows_with_parameters.keys()):\n # user optional parameters are provided, scan them:\n dargs = {}\n for arg in list(kargs.keys()):\n # check that the parameters are valid, and obtain the default value\n try:\n default = windows_with_parameters[name][arg]\n except:\n raise ValueError(\"\"\"\n Invalid optional argument (%s) for %s window.\n Valid optional arguments are (%s)\"\"\" % \\\n (arg, name, list(windows_with_parameters[name].keys())))\n # add the user parameter to the list of parameters\n dargs[arg] = kargs.get(arg, default)\n # call the proper function with the optional arguments\n w = f(N, **dargs)\n\n return w", "response": "r Returns a N - point window given a valid name."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _kaiser(n, beta):\n from scipy.special import iv as besselI\n m = n - 1\n k = arange(0, m)\n k = 2. * beta / m * sqrt (k * (m - k))\n w = besselI (0, k) / besselI (0, beta)\n return w", "response": "Independant Kaiser window\n\n For the definition of the Kaiser window, see A. V. Oppenheim & R. W. Schafer, \"Discrete-Time Signal Processing\".\n\n The continuous version of width n centered about x=0 is:\n\n .. note:: 2 times slower than scipy.kaiser"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef window_kaiser(N, beta=8.6, method='numpy'):\n if N == 1:\n return ones(1)\n if method == 'numpy':\n from numpy import kaiser\n return kaiser(N, beta)\n else:\n return _kaiser(N, beta)", "response": "r A function that returns a Kaiser window with the given length and a given Bessel function."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef window_blackman(N, alpha=0.16):\n a0 = (1. - alpha)/2.\n a1 = 0.5\n a2 = alpha/2.\n\n if (N == 1):\n win = array([1.])\n else:\n k = arange(0, N)/float(N-1.)\n win = a0 - a1 * cos (2 * pi * k) + a2 * cos (4 * pi * k)\n return win", "response": "r Blackman window with N elements."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef window_chebwin(N, attenuation=50):\n import scipy.signal\n return scipy.signal.chebwin(N, attenuation)", "response": "Cheb window\n\n :param N: window length\n\n .. plot::\n :width: 80%\n :include-source:\n\n from spectrum import window_visu\n window_visu(64, 'chebwin', attenuation=50)\n\n .. seealso:: scipy.signal.chebwin, :func:`create_window`, :class:`Window`"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef window_lanczos(N):\n if N ==1:\n return ones(1)\n\n n = linspace(-N/2., N/2., N)\n win = sinc(2*n/(N-1.))\n return win", "response": "Lanczos window also known as sinc window."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef window_nuttall(N):\n a0 = 0.355768\n a1 = 0.487396\n a2 = 0.144232\n a3 = 0.012604\n\n return _coeff4(N, a0, a1, a2, a3)", "response": "r\"\"\"Nuttall tapering window\n\n :param N: window length\n\n .. math:: w(n) = a_0 - a_1 \\cos\\left(\\frac{2\\pi n}{N-1}\\right)+ a_2 \\cos\\left(\\frac{4\\pi n}{N-1}\\right)- a_3 \\cos\\left(\\frac{6\\pi n}{N-1}\\right)\n\n with :math:`a_0 = 0.355768`, :math:`a_1 = 0.487396`, :math:`a_2=0.144232` and :math:`a_3=0.012604`\n\n .. plot::\n :width: 80%\n :include-source:\n\n from spectrum import window_visu\n window_visu(64, 'nuttall', mindB=-80)\n\n\n .. seealso:: :func:`create_window`, :class:`Window`"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef window_tukey(N, r=0.5):\n assert r>=0 and r<=1 , \"r must be in [0,1]\"\n if N==1:\n return ones(1)\n\n if r == 0:\n return ones(N)\n elif r == 1:\n return window_hann(N)\n else:\n from numpy import flipud, concatenate, where\n\n ## cosine-tapered window\n x = linspace(0, 1, N)\n x1 = where(x=1-r/2\n\n\n .. seealso:: :func:`create_window`, :class:`Window`"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef window_flattop(N, mode='symmetric',precision=None):\n assert mode in ['periodic', 'symmetric']\n t = arange(0, N)\n\n # FIXME: N=1 for mode = periodic ?\n if mode == 'periodic':\n x = 2*pi*t/float(N)\n else:\n if N ==1:\n return ones(1)\n x = 2*pi*t/float(N-1)\n a0 = 0.21557895\n a1 = 0.41663158\n a2 = 0.277263158\n a3 = 0.083578947\n a4 = 0.006947368\n\n if precision == 'octave':\n #to compare with octave, same as above but less precise\n d = 4.6402\n a0 = 1./d\n a1 = 1.93/d\n a2 = 1.29/d\n a3 = 0.388/d\n a4 = 0.0322/d\n w = a0-a1*cos(x)+a2*cos(2*x)-a3*cos(3*x)+a4*cos(4*x)\n return w", "response": "r Returns a flat - top window of the given length."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef window_taylor(N, nbar=4, sll=-30):\n B = 10**(-sll/20)\n A = log(B + sqrt(B**2 - 1))/pi\n s2 = nbar**2 / (A**2 + (nbar - 0.5)**2)\n ma = arange(1,nbar)\n def calc_Fm(m):\n numer = (-1)**(m+1) * prod(1-m**2/s2/(A**2 + (ma - 0.5)**2))\n denom = 2* prod([ 1-m**2/j**2 for j in ma if j != m])\n return numer/denom\n Fm = array([calc_Fm(m) for m in ma])\n def W(n):\n return 2 * np.sum(Fm * cos(2*pi*ma*(n-N/2 + 1/2)/N)) + 1\n w = array([W(n) for n in range(N)])\n # normalize (Note that this is not described in the original text)\n scale = W((N-1)/2)\n w /= scale\n return w", "response": "Taper a window of size N with a given sll."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef window_poisson(N, alpha=2):\n n = linspace(-N/2., (N)/2., N)\n w = exp(-alpha * abs(n)/(N/2.))\n return w", "response": "r Poisson tapering window"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef window_poisson_hanning(N, alpha=2):\n w1 = window_hann(N)\n w2 = window_poisson(N, alpha=alpha)\n return w1*w2", "response": "r Hann - Poisson tapering window"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncompute the response for the frequency response of the current object.", "response": "def compute_response(self, **kargs):\n \"\"\"Compute the window data frequency response\n\n :param norm: True by default. normalised the frequency data.\n :param int NFFT: total length of the final data sets( 2048 by default. \n if less than data length, then NFFT is set to the data length*2).\n\n The response is stored in :attr:`response`.\n\n .. note:: Units are dB (20 log10) since we plot the frequency response)\n\n \"\"\"\n from numpy.fft import fft, fftshift\n\n norm = kargs.get('norm', self.norm)\n\n # do some padding. Default is max(2048, data.len*2)\n NFFT = kargs.get('NFFT', 2048)\n if NFFT < len(self.data):\n NFFT = self.data.size * 2\n\n # compute the fft modulus\n A = fft(self.data, NFFT)\n mag = abs(fftshift(A))\n\n # do we want to normalise the data\n if norm is True:\n mag = mag / max(mag)\n\n response = 20. * stools.log10(mag) # factor 20 we are looking at the response\n # not the powe\n #response = clip(response,mindB,100)\n self.__response = response"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nplot the frequency domain of the current object.", "response": "def plot_frequencies(self, mindB=None, maxdB=None, norm=True):\n \"\"\"Plot the window in the frequency domain\n\n :param mindB: change the default lower y bound\n :param maxdB: change the default upper lower bound\n :param bool norm: if True, normalise the frequency response.\n\n .. plot::\n :width: 80%\n :include-source:\n\n from spectrum.window import Window\n w = Window(64, name='hamming')\n w.plot_frequencies()\n\n \"\"\"\n from pylab import plot, title, xlim, grid, ylim, xlabel, ylabel\n # recompute the response\n self.compute_response(norm=norm)\n\n plot(self.frequencies, self.response)\n title(\"ENBW=%2.1f\" % (self.enbw))\n ylabel('Frequency response (dB)')\n xlabel('Fraction of sampling frequency')\n # define the plot limits\n xlim(-0.5, 0.5)\n y0, y1 = ylim()\n if mindB:\n y0 = mindB\n if maxdB is not None:\n y1 = maxdB\n else:\n y1 = max(self.response)\n\n ylim(y0, y1)\n\n grid(True)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef plot_window(self):\n from pylab import plot, xlim, grid, title, ylabel, axis\n x = linspace(0, 1, self.N)\n xlim(0, 1)\n plot(x, self.data)\n grid(True)\n title('%s Window (%s points)' % (self.name.capitalize(), self.N))\n ylabel('Amplitude')\n axis([0, 1, 0, 1.1])", "response": "Plot the window in the time domain"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nplot both time and frequency domain results.", "response": "def plot_time_freq(self, mindB=-100, maxdB=None, norm=True,\n yaxis_label_position=\"right\"):\n \"\"\"Plotting method to plot both time and frequency domain results.\n\n See :meth:`plot_frequencies` for the optional arguments.\n\n .. plot::\n :width: 80%\n :include-source:\n\n from spectrum.window import Window\n w = Window(64, name='hamming')\n w.plot_time_freq()\n\n \"\"\"\n from pylab import subplot, gca\n\n subplot(1, 2, 1)\n self.plot_window()\n\n subplot(1, 2, 2)\n self.plot_frequencies(mindB=mindB, maxdB=maxdB, norm=norm)\n\n if yaxis_label_position==\"left\":\n try: tight_layout()\n except: pass\n else:\n ax = gca()\n ax.yaxis.set_label_position(\"right\")"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nsolving the general toeplitz linear equations", "response": "def TOEPLITZ(T0, TC, TR, Z):\n \"\"\"solve the general toeplitz linear equations\n\n Solve TX=Z\n \n :param T0: zero lag value\n :param TC: r1 to rN \n :param TR: r1 to rN\n\n returns X\n\n requires 3M^2+M operations instead of M^3 with gaussian elimination\n \n .. warning:: not used right now\n \"\"\"\n assert len(TC)>0\n assert len(TC)==len(TR)\n M = len(TC)\n X = numpy.zeros(M+1,dtype=complex)\n A = numpy.zeros(M,dtype=complex)\n B = numpy.zeros(M,dtype=complex)\n P = T0\n if P == 0: raise ValueError(\"P must be different from zero\")\n if P == 0: raise ValueError(\"P must be different from zero\")\n X[0] = Z[0]/T0 \n for k in range(0, M):\n save1 = TC[k]\n save2 = TR[k]\n beta = X[0]*TC[k]\n if k == 0:\n temp1 = -save1 / P\n temp2 = -save2 / P\n else:\n for j in range(0, k):\n save1 = save1 + A[j] * TC[k-j-1]\n save2 = save2 + B[j] * TR[k-j-1]\n beta = beta + X[j+1] * TC[k-j-1]\n temp1 = -save1 / P\n temp2 = -save2/P\n P = P * (1. - (temp1*temp2))\n if P <= 0:\n raise ValueError(\"singular matrix\")\n A[k] = temp1\n B[k] = temp2\n alpha = (Z[k+1]-beta)/P\n if k == 0: \n X[k+1] = alpha\n for j in range(0,k+1):\n X[j] = X[j] + alpha * B[k-j]\n continue\n \n for j in range(0, k):\n kj = k-j-1\n save1 = A[j]\n A[j] = save1 + temp1 * B[kj] \n B[kj] = B[kj] + temp2*save1\n \n X[k+1] = alpha\n for j in range(0,k+1):\n X[j] = X[j] + alpha*B[k-j]\n return X"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_short_module_name(module_name, obj_name):\n parts = module_name.split('.')\n short_name = module_name\n for i in range(len(parts) - 1, 0, -1):\n short_name = '.'.join(parts[:i])\n try:\n exec('from %s import %s' % (short_name, obj_name))\n except ImportError:\n # get the last working module name\n short_name = '.'.join(parts[:(i + 1)])\n break\n return short_name", "response": "Get the shortest possible module name for a given object name."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nidentifying and resolve used names in a codeobj.", "response": "def identify_names(code):\n \"\"\"Builds a codeobj summary by identifying and resolving used names\n\n >>> code = '''\n ... from a.b import c\n ... import d as e\n ... print(c)\n ... e.HelloWorld().f.g\n ... '''\n >>> for name, o in sorted(identify_names(code).items()):\n ... print(name, o['name'], o['module'], o['module_short'])\n c c a.b a.b\n e.HelloWorld HelloWorld d d\n \"\"\"\n finder = NameFinder()\n finder.visit(ast.parse(code))\n\n example_code_obj = {}\n for name, full_name in finder.get_mapping():\n # name is as written in file (e.g. np.asarray)\n # full_name includes resolved import path (e.g. numpy.asarray)\n module, attribute = full_name.rsplit('.', 1)\n # get shortened module name\n module_short = get_short_module_name(module, attribute)\n cobj = {'name': attribute, 'module': module,\n 'module_short': module_short}\n example_code_obj[name] = cobj\n return example_code_obj"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngenerates RST to place a thumbnail in a gallery", "response": "def _thumbnail_div(full_dir, fname, snippet, is_backref=False):\n \"\"\"Generates RST to place a thumbnail in a gallery\"\"\"\n thumb = os.path.join(full_dir, 'images', 'thumb',\n 'sphx_glr_%s_thumb.png' % fname[:-3])\n ref_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')\n\n template = BACKREF_THUMBNAIL_TEMPLATE if is_backref else THUMBNAIL_TEMPLATE\n return template.format(snippet=snippet, thumbnail=thumb, ref_name=ref_name)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef modcovar_marple (X,IP):\n Pv = []\n N = len(X)\n A = np.zeros(N, dtype=complex)\n D = np.zeros(N, dtype=complex)\n C = np.zeros(N, dtype=complex)\n R = np.zeros(N, dtype=complex)\n # Initialization\n R1=0.\n for K in range(1, N-1):\n R1=R1 + 2.*(X[K].real**2 + X[K].imag**2)\n R2 = X[0].real**2 + X[0].imag**2\n R3 = X[N-1].real**2 + X[N-1].imag**2\n R4 = 1. / (R1 + 2. * (R2 + R3))\n P = R1 + R2 + R3\n DELTA = 1. - R2 * R4\n GAMMA = 1. - R3 * R4\n LAMBDA = (X[0] * X[N-1]).conjugate()*R4\n C[0] = X[N-1] * R4\n D[0] = X[0].conjugate() * R4\n\n M = 0\n if (IP ==0):\n P = (.5*R1+R2+R3)/float(N)\n return [], P, []\n\n #C Main loop\n\n for M in range(0, IP):\n #print '---------------------', M\n SAVE1 = 0+0j\n for K in range(M+1, N):\n SAVE1 = SAVE1 + X[K]*X[K-M-1].conjugate()\n SAVE1 *= 2.\n R[M] = SAVE1.conjugate()\n THETA = X[N-1]*D[0]\n PSI=X[N-1]*C[0]\n XI = X[0].conjugate() * D[0]\n if M==0:\n pass\n else:\n for K in range(0, M):\n THETA=THETA+X[N-K-2]*D[K+1] # Eq. (8.D.45)\n PSI = PSI + X[N-K-2]*C[K+1] # Eq. (8.D.45)\n XI = XI + X[K+1].conjugate() * D[K+1] # Eq. (8.D.45)\n R[K] = R[K]-X[N-M-1] * X[N+1-M+K-1].conjugate() - X[M].conjugate() * X[M-K-1] # Eq. (8.D.37)\n SAVE1=SAVE1+R[K].conjugate()*A[M-K-1] # Eq. (8.D.24)\n #print 'withini loop', K, THETA, PSI, XI, R[K], SAVE1\n #print 'x -------', C[K], C[K+1]\n #print 'x -------', D[K], D[K+1]\n #print 'x -------', N-K-2, K+1,N-M-1, M, M-K-1\n #print 'x -------', X[N-K-2], X[K+1],X[N-M-1], X[M], X[M-K-1]\n\n\n # Order update of A vector\n\n C1 = -SAVE1/P\n A[M]=C1 # Eq. (8.D.23)\n P=P*(1.-C1.real**2-C1.imag**2) # Eq. (8.D.25)\n #print 'C1=' , C1, 'A[M]', A[M], 'P=',P\n if M==0:\n pass\n else:\n #for k in range(0, (M-1)/2+1):\n #print 'BEFORE', A[0:4]\n for K in range(0, (M+1)//2):\n MK = M-K-1\n SAVE1=A[K]\n A[K]=SAVE1+C1*A[MK].conjugate() # Eq. (8.D.22)\n #print 'A uopdate---->',M, K, MK, A[K], A[MK], SAVE1, C1\n if (K != MK):\n #print 'ENTERI IF', K, MK, A[MK], C1, SAVE1\n A[MK]=A[MK]+C1*(SAVE1.conjugate()) # Eq. (8.D.22)\n #print 'AFTER', A[0:4]\n #print M+1, IP\n if M+1 == IP:\n #Pv.append(P)\n P=.5*P/float(N-M-1)\n Pv.append(P)\n return A, P, Pv\n else:\n Pv.append(.5*P/float(N-M-1))\n #Pv.append(P)\n\n # Time update of C,D vectors and GAMMA,DELTA,LAMBDA scalars\n\n R1=1./(DELTA*GAMMA-(LAMBDA.real)**2-(LAMBDA.imag)**2)\n C1=(THETA*(LAMBDA.conjugate())+PSI*DELTA)*R1\n C2=(PSI*LAMBDA+THETA*GAMMA)*R1\n C3=(XI*(LAMBDA.conjugate())+THETA*DELTA)*R1\n C4=(THETA*LAMBDA+XI*GAMMA)*R1\n\n #print 'C1C2C3C4', C1, C2, C3, C4\n #print M, M/2+1, (M-1)/2+1\n for K in range(0, (M)//2+1):\n MK=M-K\n SAVE1=C[K].conjugate()\n SAVE2=D[K].conjugate()\n SAVE3=C[MK].conjugate()\n SAVE4=D[MK].conjugate()\n C[K]=C[K]+C1*SAVE3+C2*SAVE4 # Eq. (8.D.43)\n D[K]=D[K]+C3*SAVE3+C4*SAVE4 # Eq. (8.D.44)\n #print '-------->', K,MK, SAVE1, SAVE2, SAVE3, SAVE4\n if K != MK:\n C[MK]=C[MK]+C1*SAVE1+C2*SAVE2 # Eq. (8.D.43)\n D[MK]=D[MK]+C3*SAVE1+C4*SAVE2 # Eq. (8.D.44)\n #print 'witninloop loop ',K,MK,C[MK], D[MK]\n #print 'after loop'\n #print 'C=',C[0:2]\n #print 'D=',D[0:2]\n R2=PSI.real**2+PSI.imag**2\n R3=THETA.real**2+THETA.imag**2\n R4=XI.real**2+XI.imag**2\n R5=GAMMA-(R2*DELTA+R3*GAMMA+2.*np.real(PSI*LAMBDA*THETA.conjugate()))*R1\n R2=DELTA-(R3*DELTA+R4*GAMMA+2.*np.real(THETA*LAMBDA*XI.conjugate()))*R1\n GAMMA=R5 # Eq. (8.D.46)\n DELTA=R2 # Eq. (8.D.47)\n LAMBDA=LAMBDA+C3*PSI.conjugate()+C4*THETA.conjugate() # Eq. (8.D.48)\n #print 'before time updaqt',R2, R3, R4, R5, LAMBDA\n if P <= 0.:\n raise ValueError('Found an invalid negative value for P.')\n if (DELTA > 0. and DELTA <= 1. and GAMMA > 0. and GAMMA <=1.):\n pass\n else:\n raise ValueError('Found an invalid DELTA or GAMMA value.')\n # Time update of A vector; order updates of C,D vectors aand GAMMA,\n # DELTA,LAMBDA scalars\n #print 'time update--------------'\n R1=1./P\n R2=1./(DELTA*GAMMA-LAMBDA.real**2-LAMBDA.imag**2) # Eq. (8.D.41)\n EF=X[M+1]\n EB=X[N-M-2]\n #print 'efeb', EF, EB\n #print 'A=',A[0:2]\n for K in range(0, M+1):\n #print 'efeb lloop', K,A[K], X[M-K], X[N-M+K-1]\n EF=EF+A[K]*X[M-K] # Eq. (8.D.1)\n EB=EB+A[K].conjugate()*X[N-M+K-1] # Eq. (8.D.2)\n C1=EB*R1 # Eq. (8.D.28)\n C2=EF.conjugate()*R1 # Eq. (8.D.29)\n C3=(EB.conjugate()*DELTA+EF*LAMBDA)*R2\n C4=(EF*GAMMA+(EB*LAMBDA).conjugate())*R2\n\n #print 'c1c2c3c4', C1 ,C2, C3, C4\n #print 'efeb',EF, EB\n\n for K in range(M, -1, -1):\n SAVE1=A[K]\n A[K]=SAVE1+C3*C[K]+C4*D[K] # Eq. (8.D.38)\n C[K+1]=C[K]+C1*SAVE1 # Eq. (8.D.26)\n D[K+1]=D[K]+C2*SAVE1 # Eq. (8.D.27)\n #print 'ACD',K, A[K], C[K+1], D[K+1]\n C[0]=C1\n D[0]=C2\n R3=EB.real**2+EB.imag**2\n R4=EF.real**2+EF.imag**2\n P=P-(R3*DELTA+R4*GAMMA+2.*np.real(EF*EB*LAMBDA))*R2 # Eq. (8.D.42)\n DELTA=DELTA-R4*R1 # Eq. (8.D.32)\n GAMMA=GAMMA-R3*R1 # Eq. (8.D.33)\n LAMBDA=LAMBDA+(EF*EB).conjugate()*R1 # Eq. (8.D.35)\n\n #print 'final'\n #print R3, R4, P, DELTA, GAMMA, LAMBDA\n #print 'Afinal=',A[0:2]\n #print 'P=',P\n if (P > 0.):\n pass\n else:\n raise ValueError(\"Found a invalid negative P value \")\n if (DELTA > 0. and DELTA <= 1. and GAMMA > 0. and GAMMA <= 1.):\n pass\n else:\n raise ValueError(\"Found an invalid negative GAMMA or DELTA value \")", "response": "Fast algorithm for the modified covariance least squares normal equations."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef modcovar(x, order):\n from spectrum import corrmtx\n import scipy.linalg\n X = corrmtx(x, order, 'modified')\n Xc = np.matrix(X[:,1:])\n X1 = np.array(X[:,0])\n\n # Coefficients estimated via the covariance method\n # Here we use lstsq rathre than solve function because Xc is not square matrix\n a, residues, rank, singular_values = scipy.linalg.lstsq(-Xc, X1)\n\n # Estimate the input white noise variance\n\n\n Cz = np.dot(X1.conj().transpose(), Xc)\n e = np.dot(X1.conj().transpose(), X1) + np.dot(Cz, a)\n assert e.imag < 1e-4, 'wierd behaviour'\n e = float(e.real) # ignore imag part that should be small\n\n return a, e", "response": "Simple and fast implementation of the covariance AR estimate of the real and imaginary noise of the given complex data samples."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef aryule(X, order, norm='biased', allow_singularity=True):\n assert norm in ['biased', 'unbiased']\n r = CORRELATION(X, maxlags=order, norm=norm)\n A, P, k = LEVINSON(r, allow_singularity=allow_singularity)\n return A, P, k", "response": "r Returns the polynomial A corresponding to the set of complex data values X to X."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncomputing the autocorrelation coefficients R based on the prediction polynomial A and the final prediction error Efinal.", "response": "def rlevinson(a, efinal):\n \"\"\"computes the autocorrelation coefficients, R based\n on the prediction polynomial A and the final prediction error Efinal,\n using the stepdown algorithm.\n\n Works for real or complex data\n\n :param a:\n :param efinal:\n\n :return:\n * R, the autocorrelation\n * U prediction coefficient\n * kr reflection coefficients\n * e errors\n\n A should be a minimum phase polynomial and A(1) is assumed to be unity.\n\n :returns: (P+1) by (P+1) upper triangular matrix, U,\n that holds the i'th order prediction polynomials\n Ai, i=1:P, where P is the order of the input\n polynomial, A.\n\n\n\n [ 1 a1(1)* a2(2)* ..... aP(P) * ]\n [ 0 1 a2(1)* ..... aP(P-1)* ]\n U = [ .................................]\n [ 0 0 0 ..... 1 ]\n\n from which the i'th order prediction polynomial can be extracted\n using Ai=U(i+1:-1:1,i+1)'. The first row of U contains the\n conjugates of the reflection coefficients, and the K's may be\n extracted using, K=conj(U(1,2:end)).\n\n .. todo:: remove the conjugate when data is real data, clean up the code\n test and doc.\n\n \"\"\"\n a = numpy.array(a)\n realdata = numpy.isrealobj(a)\n\n\n assert a[0] == 1, 'First coefficient of the prediction polynomial must be unity'\n\n p = len(a)\n\n if p < 2:\n raise ValueError('Polynomial should have at least two coefficients')\n\n if realdata == True:\n U = numpy.zeros((p, p)) # This matrix will have the prediction\n # polynomials of orders 1:p\n else:\n U = numpy.zeros((p, p), dtype=complex)\n U[:, p-1] = numpy.conj(a[-1::-1]) # Prediction coefficients of order p\n\n p = p -1\n e = numpy.zeros(p)\n\n # First we find the prediction coefficients of smaller orders and form the\n # Matrix U\n\n # Initialize the step down\n\n e[-1] = efinal # Prediction error of order p\n\n # Step down\n for k in range(p-1, 0, -1):\n [a, e[k-1]] = levdown(a, e[k])\n U[:, k] = numpy.concatenate((numpy.conj(a[-1::-1].transpose()) ,\n [0]*(p-k) ))\n\n\n\n\n e0 = e[0]/(1.-abs(a[1]**2)) #% Because a[1]=1 (true polynomial)\n U[0,0] = 1 #% Prediction coefficient of zeroth order\n kr = numpy.conj(U[0,1:]) #% The reflection coefficients\n kr = kr.transpose() #% To make it into a column vector\n\n # % Once we have the matrix U and the prediction error at various orders, we can\n # % use this information to find the autocorrelation coefficients.\n\n R = numpy.zeros(1, dtype=complex)\n #% Initialize recursion\n k = 1\n R0 = e0 # To take care of the zero indexing problem\n R[0] = -numpy.conj(U[0,1])*R0 # R[1]=-a1[1]*R[0]\n\n # Actual recursion\n for k in range(1,p):\n r = -sum(numpy.conj(U[k-1::-1,k])*R[-1::-1]) - kr[k]*e[k-1]\n R = numpy.insert(R, len(R), r)\n\n # Include R(0) and make it a column vector. Note the dot transpose\n\n #R = [R0 R].';\n R = numpy.insert(R, 0, e0)\n return R, U, kr, e"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef levup(acur, knxt, ecur=None):\n if acur[0] != 1:\n raise ValueError('At least one of the reflection coefficients is equal to one.')\n acur = acur[1:] # Drop the leading 1, it is not needed\n\n # Matrix formulation from Stoica is used to avoid looping\n anxt = numpy.concatenate((acur, [0])) + knxt * numpy.concatenate((numpy.conj(acur[-1::-1]), [1]))\n\n enxt = None\n if ecur is not None:\n # matlab version enxt = (1-knxt'.*knxt)*ecur\n enxt = (1. - numpy.dot(numpy.conj(knxt), knxt)) * ecur\n\n anxt = numpy.insert(anxt, 0, 1)\n\n return anxt, enxt", "response": "One step forward Levinson recursion\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef arcovar_marple(x, order):\n assert len(x) >= order, \"X must be dimensioned >=N\"\n\n # ----------------------------------------------------- Initialization\n x = np.array(x)\n N = len(x)\n\n\n # Equations 8.C.42\n r0 = sum(abs(x)**2.)\n r1 = abs(x[0])**2\n rN = abs(x[N-1])**2\n\n pf = r0 - r1\n pb = r0 - rN\n\n delta = 1. - r1 / r0\n gamma = 1. - rN / r0\n\n c = np.zeros(N, dtype=complex)\n d = np.zeros(N, dtype=complex)\n r = np.zeros(N, dtype=complex)\n af = np.zeros(N, dtype=complex)\n ab = np.zeros(N, dtype=complex)\n\n c[0] = x[N-1].conjugate() / r0\n d[0] = x[0].conjugate() / r0\n\n # special case\n if order == 0:\n pf = r0 / float(N)\n pb = pf\n return af, pf, ab, pb, 0\n\n # ---------------------------------------------------------- MAIN LOOP\n\n #ip +1 because we want to enter in the loop to run the first part of the code.\n pbv = []\n for m in range(0, order+1):\n logging.debug('----------------------------m=', m)\n logging.debug(c[0:2])\n logging.debug(d[0:2])\n r1 = 1./pf\n r2 = 1./pb\n r3 = 1./delta\n r4 = 1./gamma\n\n #logging.debug('starting r1r2r3r4=', r1, r2, r3, r4, pf, pb, delta, gamma)\n\n #Order update: AF and AB vectors ; time update: C and D vectors\n temp = 0.+0.j\n for k in range(m+1, N):\n temp = temp + x[k]*x[k-m-1].conjugate()\n\n r[m] = temp.conjugate()\n theta = x[0] * c[m]\n #print(('theta', theta))\n # print(('c=', c[0:2]))\n # print(('d=', d[0:2]))\n if m == 0:\n pass\n else:\n for k in range(0, m):\n theta = theta + x[m-k] * c[k] # Eq. (8.C.39)\n r[k] = r[k] - x[N-m-1] * x[N-m+k].conjugate() # Eq. (8.C.32)\n temp = temp + af[m-k-1] * r[k].conjugate()\n #print 'loop1 k=', k\n #print ' theta=',theta, 'r[k]=',r[k], 'temp=', temp\n #print ' c=',c[k], 'af=',af[m-k-1]\n \"\"\"if m > 0:\n if debug:\n print((m, N-m))\n print(('Xk=0',x[m-0],x[N-m-1], x[N-m+0]))\n if m > 1:\n if debug:\n print('Xk=1',x[m-1],x[N-m-1], x[N-m+1])\n \"\"\"\n c1 = -temp * r2\n c2 = -r1 * temp.conjugate()\n c3 = theta * r3\n c4 = r4 *theta.conjugate()\n #if debug:\n # print('c1 c2 c3 c4 before af=',c1 ,c2 ,c3 ,c4)\n af[m] = c1 # ! Eq. (8.C.19)\n ab[m] = c2 # ! Eq. (8.C.22)\n save = c[m]\n c[m] = save + c3*d[m]\n d[m] = d[m] + c4*save\n #if debug:\n # print('res',m,'af[m]=',af[m], ab[m], save, 'temp=',temp)\n\n if m == 0:\n pass\n else:\n #if debug:print('af before', af[0:2])\n for k in range(0, m):\n save = af[k]\n af[k] = save + c1 * ab[m-k-1] # Eq. (8.C.18)\n ab[m-k-1] = ab[m-k-1] + c2 * save # Eq. (8.C.21)\n\n save = c[k]\n c[k] = save + c3*d[k] # Eq. (8.C.37)\n d[k] = d[k] + c4*save # Eq. (8.C.38)\n #if debug:\n # print('loop2 k=', k)\n # print(' af[k]=', af[k])\n # print(' ab[m-k-1]=', ab[m-k-1])\n # print(' c[k]=', c[k])\n # print(' d[k]=', d[k])\n #if debug:\n # print('af after=', af[0:2])\n # print('ab=', ab[0:2])\n\n r5 = temp.real**2 + temp.imag**2\n pf = pf - r5*r2 # Eq. (8.C.20)\n pb = pb - r5*r1 # Eq. (8.C.23)\n r5 = theta.real**2 + theta.imag**2\n delta = delta - r5*r4 # Eq. (8.C.39)\n gamma = gamma - r5*r3 # Eq. (8.C.40)\n #if debug:\n # print('r5r2r1deltagamma', r5, r2, r1 , delta, gamma)\n # print('pf before norm', pf, pb, N-m-1)\n if m != order-1:\n pass\n else:\n pf = pf / float(N-m-1)\n pb = pb / float(N-m-1)\n #if debug:\n # print('ENDING', N-m-1)\n break\n\n #if debug:\n # print('pf and pb', pf, pb)\n if pf > 0 and pb > 0:\n pass\n else:\n ValueError(\"Negative PF or PB value\")\n if (delta > 0. and delta <=1 and gamma > 0. and gamma <=1):\n pass\n else:\n ValueError(\"Invalid delta or gamma value\")\n\n #C Time update: AF and AB vectors; order update: C and D vectors\n\n r1 = 1./pf\n r2 = 1./pb\n r3 = 1./delta\n r4 = 1./gamma\n #if debug:\n # print('--------time update', r1, r2, r3, r4, m+1, N-m-1, x[m+1], x[N-m-2])\n ef = x[m+1]\n eb = x[(N-1)-m-1]\n\n\n for k in range(0,m+1):\n #print 'k=', k, 'ef=', ef, ' eb=',eb,' af=',af[k], ab[k]\n #print x[m-k],x[N-m+k-1]\n ef = ef + af[k] * x[m-k] # Eq. (8.C.1)\n eb = eb + ab[k] * x[N-m+k-1] # Eq. (8.C.2)\n\n #ef = sum(af)\n\n #if debug:\n # print('efweb', ef , eb)\n c1 = ef*r3\n c2 = eb*r4\n c3 = eb.conjugate() * r2\n c4 = ef.conjugate() * r1\n #if debug:\n # print('c1c2c3c4', c1, c2, c3, c4)\n # print('af before', af[0:2])\n for k in range(m, -1, -1):\n save = af[k]\n af[k] = save + c1 * d[k] # Eq. (8.C.33)\n d[k+1] = d[k] + c4 * save # Eq. (8.C.25)\n save = ab[k]\n ab[k] = save + c2 * c[m-k] # Eq. (8.C.35)\n c[m-k] = c[m-k] + c3 * save # Eq. (8.C.24)\n #if debug:\n # print('af after', af[0:2])\n # print('d', d[0:2])\n # print('ab', ab[0:2])\n # print('c', c[0:2])\n #if debug:print('Pb before', pf, pb)\n c[m+1] = c3\n d[0] = c4\n #r5 = abs(ef)**2\n r5 = ef.real**2 + ef.imag**2\n pf = pf - r5 * r3 # Eq. (8.C.34)\n\n delta = delta-r5 * r1 # Eq. (8.C.30)\n #r5 = abs(eb)**2\n r5 = eb.real**2 + eb.imag**2\n pb = pb - r5 * r4 # Eq. (8.C.36)\n #if debug:\n # print('Pb---------------------', m, pb, r5, r4)\n gamma = gamma-r5*r2 # Eq. (8.C.31)\n pbv.append(pb)\n\n if (pf > 0. and pb > 0.):\n pass\n else:\n ValueError(\"Negative PF or PB value\")\n #if debug:\n # print(delta, gamma)\n if (delta > 0. and delta <= 1.) and (gamma > 0. and gamma <= 1.):\n pass\n else:\n ValueError(\"Invalid delta or gamma value\")\n\n\n #af=array of forward coeff\n #ab=array of barward coeff\n #pb=backward variance\n #pf=forward variance\n return af, pf, ab, pb, pbv", "response": "r Estimates AR model parameters using covariance method Marple."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef arcovar(x, order):\n\n from spectrum import corrmtx\n import scipy.linalg\n\n X = corrmtx(x, order, 'covariance')\n Xc = np.matrix(X[:, 1:])\n X1 = np.array(X[:, 0])\n\n # Coefficients estimated via the covariance method\n # Here we use lstsq rathre than solve function because Xc is not square\n # matrix\n\n a, _residues, _rank, _singular_values = scipy.linalg.lstsq(-Xc, X1)\n\n # Estimate the input white noise variance\n Cz = np.dot(X1.conj().transpose(), Xc)\n e = np.dot(X1.conj().transpose(), X1) + np.dot(Cz, a)\n assert e.imag < 1e-4, 'wierd behaviour'\n e = float(e.real) # ignore imag part that should be small\n\n return a, e", "response": "r Simple and fast implementation of the covariance AR estimate\n "}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef lpc(x, N=None):\n\n m = len(x)\n if N is None:\n N = m - 1 #default value if N is not provided\n elif N > m-1:\n #disp('Warning: zero-padding short input sequence')\n x.resize(N+1)\n #todo: check this zero-padding.\n\n X = fft(x, 2**nextpow2(2.*len(x)-1))\n R = real(ifft(abs(X)**2))\n R = R/(m-1.) #Biased autocorrelation estimate\n a, e, ref = LEVINSON(R, N)\n return a, e", "response": "Linear Predictor Coefficients.\n\n :param x:\n :param int N: default is length(X) - 1\n\n :Details:\n\n Finds the coefficients :math:`A=(1, a(2), \\dots a(N+1))`, of an Nth order\n forward linear predictor that predicts the current value value of the\n real-valued time series x based on past samples:\n\n .. math:: \\hat{x}(n) = -a(2)*x(n-1) - a(3)*x(n-2) - ... - a(N+1)*x(n-N)\n\n such that the sum of the squares of the errors\n\n .. math:: err(n) = X(n) - Xp(n)\n\n is minimized. This function uses the Levinson-Durbin recursion to\n solve the normal equations that arise from the least-squares formulation.\n\n .. seealso:: :func:`levinson`, :func:`aryule`, :func:`prony`, :func:`stmcb`\n\n .. todo:: matrix case, references\n\n :Example:\n\n ::\n\n from scipy.signal import lfilter\n noise = randn(50000,1); % Normalized white Gaussian noise\n x = filter([1], [1 1/2 1/3 1/4], noise)\n x = x[45904:50000]\n x.reshape(4096, 1)\n x = x[0]\n\n Compute the predictor coefficients, estimated signal, prediction error, and autocorrelation sequence of the prediction error:\n\n\n 1.00000 + 0.00000i 0.51711 - 0.00000i 0.33908 - 0.00000i 0.24410 - 0.00000i\n\n ::\n\n a = lpc(x, 3)\n est_x = lfilter([0 -a(2:end)],1,x); % Estimated signal\n e = x - est_x; % Prediction error\n [acs,lags] = xcorr(e,'coeff'); % ACS of prediction error"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn Pascal matrix of n words.", "response": "def pascal(n):\n \"\"\"Return Pascal matrix\n\n :param int n: size of the matrix\n\n .. doctest::\n\n >>> from spectrum import pascal\n >>> pascal(6)\n array([[ 1., 1., 1., 1., 1., 1.],\n [ 1., 2., 3., 4., 5., 6.],\n [ 1., 3., 6., 10., 15., 21.],\n [ 1., 4., 10., 20., 35., 56.],\n [ 1., 5., 15., 35., 70., 126.],\n [ 1., 6., 21., 56., 126., 252.]])\n\n .. todo:: use the symmetric property to improve computational time if needed\n \"\"\"\n errors.is_positive_integer(n)\n result = numpy.zeros((n, n))\n\n #fill the first row and column\n for i in range(0, n):\n result[i, 0] = 1\n result[0, i] = 1\n if n > 1:\n for i in range(1, n):\n for j in range(1, n):\n result[i, j] = result[i-1, j] + result[i, j-1]\n return result"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef csvd(A):\n U, S, V = numpy.linalg.svd(A)\n return U, S, V", "response": "SVD decomposition using numpy. linalg. svd"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ntries to return a path to static the way back to Django 1. 2.", "response": "def compatible_staticpath(path):\n \"\"\"\n Try to return a path to static the static files compatible all\n the way back to Django 1.2. If anyone has a cleaner or better\n way to do this let me know!\n \"\"\"\n\n if VERSION >= (1, 10):\n # Since Django 1.10, forms.Media automatically invoke static\n # lazily on the path if it is relative.\n return path\n try:\n # >= 1.4\n from django.templatetags.static import static\n return static(path)\n except ImportError:\n pass\n try:\n # >= 1.3\n return '%s/%s' % (settings.STATIC_URL.rstrip('/'), path)\n except AttributeError:\n pass\n try:\n return '%s/%s' % (settings.PAGEDOWN_URL.rstrip('/'), path)\n except AttributeError:\n pass\n return '%s/%s' % (settings.MEDIA_URL.rstrip('/'), path)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef main(argv=None):\n\n if argv is None:\n argv = sys.argv[1:]\n\n cli = CommandLineTool()\n return cli.run(argv)", "response": "Main command line interface."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning True if user is on pipe False otherwise.", "response": "def pass_from_pipe(cls):\n \"\"\"Return password from pipe if not on TTY, else False.\n \"\"\"\n is_pipe = not sys.stdin.isatty()\n return is_pipe and cls.strip_last_newline(sys.stdin.read())"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nloads all setuptools entry points by the name keyring backends and initialize them.", "response": "def _load_plugins():\n \"\"\"\n Locate all setuptools entry points by the name 'keyring backends'\n and initialize them.\n Any third-party library may register an entry point by adding the\n following to their setup.py::\n\n entry_points = {\n 'keyring.backends': [\n 'plugin_name = mylib.mymodule:initialize_func',\n ],\n },\n\n `plugin_name` can be anything, and is only used to display the name\n of the plugin at initialization time.\n\n `initialize_func` is optional, but will be invoked if callable.\n \"\"\"\n group = 'keyring.backends'\n entry_points = entrypoints.get_group_all(group=group)\n for ep in entry_points:\n try:\n log.info('Loading %s', ep.name)\n init_func = ep.load()\n if callable(init_func):\n init_func()\n except Exception:\n log.exception(\"Error initializing plugin %s.\" % ep)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get_all_keyring():\n _load_plugins()\n viable_classes = KeyringBackend.get_viable_backends()\n rings = util.suppress_exceptions(viable_classes, exceptions=TypeError)\n return list(rings)", "response": "Returns a list of all implemented keyrings that can be constructed without parameter."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngetting the username and password for the service.", "response": "def get_credential(self, service, username):\n \"\"\"Gets the username and password for the service.\n Returns a Credential instance.\n\n The *username* argument is optional and may be omitted by\n the caller or ignored by the backend. Callers must use the\n returned username.\n \"\"\"\n # The default implementation requires a username here.\n if username is not None:\n password = self.get_password(service, username)\n if password is not None:\n return credentials.SimpleCredential(\n username,\n password,\n )\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_password(self, service, username):\n if not self.connected(service):\n # the user pressed \"cancel\" when prompted to unlock their keyring.\n raise KeyringLocked(\"Failed to unlock the keyring!\")\n if not self.iface.hasEntry(self.handle, service, username, self.appid):\n return None\n password = self.iface.readPassword(\n self.handle, service, username, self.appid)\n return str(password)", "response": "Get the password for the username for the service"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nset the password for the username of the service", "response": "def set_password(self, service, username, password):\n \"\"\"Set password for the username of the service\n \"\"\"\n if not self.connected(service):\n # the user pressed \"cancel\" when prompted to unlock their keyring.\n raise PasswordSetError(\"Cancelled by user\")\n self.iface.writePassword(\n self.handle, service, username, password, self.appid)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef delete_password(self, service, username):\n if not self.connected(service):\n # the user pressed \"cancel\" when prompted to unlock their keyring.\n raise PasswordDeleteError(\"Cancelled by user\")\n if not self.iface.hasEntry(self.handle, service, username, self.appid):\n raise PasswordDeleteError(\"Password not found\")\n self.iface.removeEntry(self.handle, service, username, self.appid)", "response": "Delete the password for the username of the service."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the preferred collection for this instance.", "response": "def get_preferred_collection(self):\n \"\"\"If self.preferred_collection contains a D-Bus path,\n the collection at that address is returned. Otherwise,\n the default collection is returned.\n \"\"\"\n bus = secretstorage.dbus_init()\n try:\n if hasattr(self, 'preferred_collection'):\n collection = secretstorage.Collection(\n bus, self.preferred_collection)\n else:\n collection = secretstorage.get_default_collection(bus)\n except exceptions.SecretStorageException as e:\n raise InitError(\"Failed to create the collection: %s.\" % e)\n if collection.is_locked():\n collection.unlock()\n if collection.is_locked(): # User dismissed the prompt\n raise KeyringLocked(\"Failed to unlock the collection!\")\n return collection"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_password(self, service, username):\n collection = self.get_preferred_collection()\n items = collection.search_items(\n {\"username\": username, \"service\": service})\n for item in items:\n if hasattr(item, 'unlock'):\n item.unlock()\n if item.is_locked(): # User dismissed the prompt\n raise KeyringLocked('Failed to unlock the item!')\n return item.get_secret().decode('utf-8')", "response": "Get the password of the username for the service"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsetting the password for the username of the service", "response": "def set_password(self, service, username, password):\n \"\"\"Set password for the username of the service\n \"\"\"\n collection = self.get_preferred_collection()\n attributes = {\n \"application\": self.appid,\n \"service\": service,\n \"username\": username\n }\n label = \"Password for '{}' on '{}'\".format(username, service)\n collection.create_item(label, attributes, password, replace=True)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef delete_password(self, service, username):\n collection = self.get_preferred_collection()\n items = collection.search_items(\n {\"username\": username, \"service\": service})\n for item in items:\n return item.delete()\n raise PasswordDeleteError(\"No such password!\")", "response": "Delete the stored password"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef backends(cls):\n allowed = (\n keyring\n for keyring in filter(backend._limit, backend.get_all_keyring())\n if not isinstance(keyring, ChainerBackend)\n and keyring.priority > 0\n )\n return sorted(allowed, key=backend.by_priority, reverse=True)", "response": "Return a list of all available Chainer backends."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nset the current keyring backend.", "response": "def set_keyring(keyring):\n \"\"\"Set current keyring backend.\n \"\"\"\n global _keyring_backend\n if not isinstance(keyring, backend.KeyringBackend):\n raise TypeError(\"The keyring must be a subclass of KeyringBackend\")\n _keyring_backend = keyring"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef disable():\n root = platform.config_root()\n try:\n os.makedirs(root)\n except OSError:\n pass\n filename = os.path.join(root, 'keyringrc.cfg')\n if os.path.exists(filename):\n msg = \"Refusing to overwrite {filename}\".format(**locals())\n raise RuntimeError(msg)\n with open(filename, 'w') as file:\n file.write('[backend]\\ndefault-keyring=keyring.backends.null.Keyring')", "response": "Disable the null keyring as the default."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ninitializes the backend with the best available keyring.", "response": "def init_backend(limit=None):\n \"\"\"\n Load a keyring specified in the config file or infer the best available.\n\n Limit, if supplied, should be a callable taking a backend and returning\n True if that backend should be included for consideration.\n \"\"\"\n # save the limit for the chainer to honor\n backend._limit = limit\n\n # get all keyrings passing the limit filter\n keyrings = filter(limit, backend.get_all_keyring())\n\n set_keyring(\n load_env()\n or load_config()\n or max(keyrings, default=fail.Keyring(), key=backend.by_priority)\n )"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _load_keyring_class(keyring_name):\n module_name, sep, class_name = keyring_name.rpartition('.')\n __import__(module_name)\n module = sys.modules[module_name]\n return getattr(module, class_name)", "response": "Load the keyring class indicated by name."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef load_config():\n\n filename = 'keyringrc.cfg'\n\n keyring_cfg = os.path.join(platform.config_root(), filename)\n\n if not os.path.exists(keyring_cfg):\n return\n\n config = configparser.RawConfigParser()\n config.read(keyring_cfg)\n _load_keyring_path(config)\n\n # load the keyring class name, and then load this keyring\n try:\n if config.has_section(\"backend\"):\n keyring_name = config.get(\"backend\", \"default-keyring\").strip()\n else:\n raise configparser.NoOptionError('backend', 'default-keyring')\n\n except (configparser.NoOptionError, ImportError):\n logger = logging.getLogger('keyring')\n logger.warning(\"Keyring config file contains incorrect values.\\n\"\n + \"Config file: %s\" % keyring_cfg)\n return\n\n return load_keyring(keyring_name)", "response": "Load a keyring using the config file in the config root."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _load_keyring_path(config):\n \"load the keyring-path option (if present)\"\n try:\n path = config.get(\"backend\", \"keyring-path\").strip()\n sys.path.insert(0, path)\n except (configparser.NoOptionError, configparser.NoSectionError):\n pass", "response": "load the keyring - path option ( if present"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _data_root_Linux():\n fallback = os.path.expanduser('~/.local/share')\n root = os.environ.get('XDG_DATA_HOME', None) or fallback\n return os.path.join(root, 'python_keyring')", "response": "Return the path to the data root for Linux systems."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _check_old_config_root():\n # disable the check - once is enough and avoids infinite loop\n globals()['_check_old_config_root'] = lambda: None\n config_file_new = os.path.join(_config_root_Linux(), 'keyringrc.cfg')\n config_file_old = os.path.join(_data_root_Linux(), 'keyringrc.cfg')\n if os.path.isfile(config_file_old) and not os.path.isfile(config_file_new):\n msg = (\"Keyring config exists only in the old location \"\n \"{config_file_old} and should be moved to {config_file_new} \"\n \"to work with this version of keyring.\")\n raise RuntimeError(msg.format(**locals()))", "response": "Check that the old config root is not in the new location."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ndetermine config root for Linux.", "response": "def _config_root_Linux():\n \"\"\"\n Use freedesktop.org Base Dir Specfication to determine config\n location.\n \"\"\"\n _check_old_config_root()\n fallback = os.path.expanduser('~/.local/share')\n key = 'XDG_CONFIG_HOME'\n root = os.environ.get(key, None) or fallback\n return os.path.join(root, 'python_keyring')"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a callable that outputs the data. Defaults to print.", "response": "def make_formatter(format_name):\n \"\"\"Returns a callable that outputs the data. Defaults to print.\"\"\"\n\n if \"json\" in format_name:\n from json import dumps\n import datetime\n def jsonhandler(obj): obj.isoformat() if isinstance(obj, (datetime.datetime, datetime.date)) else obj\n if format_name == \"prettyjson\":\n def jsondumps(data): return dumps(data, default=jsonhandler, indent=2, separators=(',', ': '))\n else:\n def jsondumps(data): return dumps(data, default=jsonhandler)\n\n def jsonify(data):\n if isinstance(data, dict):\n print(jsondumps(data))\n elif isinstance(data, list):\n print(jsondumps([device._asdict() for device in data]))\n else:\n print(dumps({'result': data}))\n return jsonify\n else:\n def printer(data):\n if isinstance(data, dict):\n print(data)\n else:\n for row in data:\n print(row)\n return printer"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nconstructing the ArgumentParser for the CLI", "response": "def argparser():\n \"\"\"Constructs the ArgumentParser for the CLI\"\"\"\n\n parser = ArgumentParser(prog='pynetgear')\n\n parser.add_argument(\"--format\", choices=['json', 'prettyjson', 'py'], default='prettyjson')\n\n router_args = parser.add_argument_group(\"router connection config\")\n router_args.add_argument(\"--host\", help=\"Hostname for the router\")\n router_args.add_argument(\"--user\", help=\"Account for login\")\n router_args.add_argument(\"--port\", help=\"Port exposed on the router\")\n router_args.add_argument(\"--login-v2\", help=\"Force the use of the cookie-based authentication\",\n dest=\"force_login_v2\", default=False, action=\"store_true\")\n router_args.add_argument(\n \"--password\",\n help=\"Not required with a wired connection.\" +\n \"Optionally, set the PYNETGEAR_PASSWORD environment variable\")\n router_args.add_argument(\n \"--url\", help=\"Overrides host:port and ssl with url to router\")\n router_args.add_argument(\"--no-ssl\",\n dest=\"ssl\", default=True,\n action=\"store_false\",\n help=\"Connect with https\")\n\n subparsers = parser.add_subparsers(\n description=\"Runs subcommand against the specified router\",\n dest=\"subcommand\")\n\n block_parser = subparsers.add_parser(\n \"block_device\",\n help=\"Blocks a device from connecting by mac address\")\n block_parser.add_argument(\"--mac-addr\")\n\n allow_parser = subparsers.add_parser(\n \"allow_device\",\n help=\"Allows a device with the mac address to connect\")\n allow_parser.add_argument(\"--mac-addr\")\n\n subparsers.add_parser(\"login\", help=\"Attempts to login to router.\")\n\n attached_devices = subparsers.add_parser(\"attached_devices\", help=\"Outputs all attached devices\")\n attached_devices.add_argument(\n \"-v\", \"--verbose\",\n action=\"store_true\",\n default=False,\n help=\"Choose between verbose and slower or terse and fast.\")\n\n subparsers.add_parser(\"traffic_meter\", help=\"Output router's traffic meter data\")\n\n return parser"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nruns the subcommand configured in args on the netgear session", "response": "def run_subcommand(netgear, args):\n \"\"\"Runs the subcommand configured in args on the netgear session\"\"\"\n\n subcommand = args.subcommand\n\n if subcommand == \"block_device\" or subcommand == \"allow_device\":\n return netgear.allow_block_device(args.mac_addr, BLOCK if subcommand == \"block_device\" else ALLOW)\n\n if subcommand == \"attached_devices\":\n if args.verbose:\n return netgear.get_attached_devices_2()\n else:\n return netgear.get_attached_devices()\n\n if subcommand == 'traffic_meter':\n return netgear.get_traffic_meter()\n\n if subcommand == 'login':\n return netgear.login()\n\n print(\"Unknown subcommand\")"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nscanning for devices and print results.", "response": "def main():\n \"\"\"Scan for devices and print results.\"\"\"\n\n args = argparser().parse_args(sys.argv[1:])\n password = os.environ.get('PYNETGEAR_PASSWORD') or args.password\n\n netgear = Netgear(password, args.host, args.user, args.port, args.ssl, args.url, args.force_login_v2)\n\n results = run_subcommand(netgear, args)\n formatter = make_formatter(args.format)\n\n if results is None:\n print(\"Error communicating with the Netgear router\")\n\n else:\n formatter(results)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ntries to autodetect the base URL of the router SOAP service. Returns None if it can t be found.", "response": "def autodetect_url():\n \"\"\"\n Try to autodetect the base URL of the router SOAP service.\n\n Returns None if it can't be found.\n \"\"\"\n for url in [\"http://routerlogin.net:5000\", \"https://routerlogin.net\",\n \"http://routerlogin.net\"]:\n try:\n r = requests.get(url + \"/soap/server_sa/\",\n headers=_get_soap_headers(\"Test:1\", \"test\"),\n verify=False)\n if r.status_code == 200:\n return url\n except requests.exceptions.RequestException:\n pass\n\n return None"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nget the value of the name of the element e.", "response": "def _xml_get(e, name):\n \"\"\"\n Returns the value of the subnode \"name\" of element e.\n\n Returns None if the subnode doesn't exist\n \"\"\"\n r = e.find(name)\n if r is not None:\n return r.text\n return None"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nconvert value to to_type returns default if fails.", "response": "def _convert(value, to_type, default=None):\n \"\"\"Convert value to to_type, returns default if fails.\"\"\"\n try:\n return default if value is None else to_type(value)\n except ValueError:\n # If value could not be converted\n return default"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef login(self):\n if not self.force_login_v2:\n v1_result = self.login_v1()\n if v1_result:\n return v1_result\n\n return self.login_v2()", "response": "Login to the router."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_attached_devices(self):\n _LOGGER.info(\"Get attached devices\")\n\n success, response = self._make_request(SERVICE_DEVICE_INFO,\n \"GetAttachDevice\")\n\n if not success:\n _LOGGER.error(\"Get attached devices failed\")\n return None\n\n success, node = _find_node(\n response.text,\n \".//GetAttachDeviceResponse/NewAttachDevice\")\n if not success:\n return None\n\n devices = []\n\n # Netgear inserts a double-encoded value for \"unknown\" devices\n decoded = node.text.strip().replace(UNKNOWN_DEVICE_ENCODED,\n UNKNOWN_DEVICE_DECODED)\n\n if not decoded or decoded == \"0\":\n _LOGGER.error(\"Can't parse attached devices string\")\n _LOGGER.debug(node.text.strip())\n return devices\n\n entries = decoded.split(\"@\")\n\n # First element is the total device count\n entry_count = None\n if len(entries) > 1:\n entry_count = _convert(entries.pop(0), int)\n\n if entry_count is not None and entry_count != len(entries):\n _LOGGER.info(\n \"\"\"Number of devices should \\\n be: %d but is: %d\"\"\", entry_count, len(entries))\n\n for entry in entries:\n info = entry.split(\";\")\n\n if len(info) == 0:\n continue\n\n # Not all routers will report those\n signal = None\n link_type = None\n link_rate = None\n allow_or_block = None\n\n if len(info) >= 8:\n allow_or_block = info[7]\n if len(info) >= 7:\n link_type = info[4]\n link_rate = _convert(info[5], int)\n signal = _convert(info[6], int)\n\n if len(info) < 4:\n _LOGGER.warning(\"Unexpected entry: %s\", info)\n continue\n\n ipv4, name, mac = info[1:4]\n\n devices.append(Device(name, ipv4, mac,\n link_type, signal, link_rate, allow_or_block,\n None, None, None, None))\n\n return devices", "response": "Get list of connected devices to the router."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_attached_devices_2(self):\n _LOGGER.info(\"Get attached devices 2\")\n\n success, response = self._make_request(SERVICE_DEVICE_INFO,\n \"GetAttachDevice2\")\n if not success:\n return None\n\n success, devices_node = _find_node(\n response.text,\n \".//GetAttachDevice2Response/NewAttachDevice\")\n if not success:\n return None\n\n xml_devices = devices_node.findall(\"Device\")\n devices = []\n for d in xml_devices:\n ip = _xml_get(d, 'IP')\n name = _xml_get(d, 'Name')\n mac = _xml_get(d, 'MAC')\n signal = _convert(_xml_get(d, 'SignalStrength'), int)\n link_type = _xml_get(d, 'ConnectionType')\n link_rate = _xml_get(d, 'Linkspeed')\n allow_or_block = _xml_get(d, 'AllowOrBlock')\n device_type = _convert(_xml_get(d, 'DeviceType'), int)\n device_model = _xml_get(d, 'DeviceModel')\n ssid = _xml_get(d, 'SSID')\n conn_ap_mac = _xml_get(d, 'ConnAPMAC')\n devices.append(Device(name, ip, mac, link_type, signal, link_rate,\n allow_or_block, device_type, device_model,\n ssid, conn_ap_mac))\n\n return devices", "response": "Get list of connected devices to the router with details."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_traffic_meter(self):\n _LOGGER.info(\"Get traffic meter\")\n\n def parse_text(text):\n \"\"\"\n there are three kinds of values in the returned data\n This function parses the different values and returns\n (total, avg), timedelta or a plain float\n \"\"\"\n def tofloats(lst): return (float(t) for t in lst)\n try:\n if \"/\" in text: # \"6.19/0.88\" total/avg\n return tuple(tofloats(text.split('/')))\n elif \":\" in text: # 11:14 hr:mn\n hour, mins = tofloats(text.split(':'))\n return timedelta(hours=hour, minutes=mins)\n else:\n return float(text)\n except ValueError:\n return None\n\n success, response = self._make_request(SERVICE_DEVICE_CONFIG,\n \"GetTrafficMeterStatistics\")\n if not success:\n return None\n\n success, node = _find_node(\n response.text,\n \".//GetTrafficMeterStatisticsResponse\")\n if not success:\n return None\n\n return {t.tag: parse_text(t.text) for t in node}", "response": "Get the traffic meter stats."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nstarting a configuration session.", "response": "def config_start(self):\n \"\"\"\n Start a configuration session.\n For managing router admin functionality (ie allowing/blocking devices)\n \"\"\"\n _LOGGER.info(\"Config start\")\n\n success, _ = self._make_request(\n SERVICE_DEVICE_CONFIG, \"ConfigurationStarted\", {\"NewSessionID\": SESSION_ID})\n\n self.config_started = success\n return success"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nends of a configuration session.", "response": "def config_finish(self):\n \"\"\"\n End of a configuration session.\n Tells the router we're done managing admin functionality.\n \"\"\"\n _LOGGER.info(\"Config finish\")\n if not self.config_started:\n return True\n\n success, _ = self._make_request(\n SERVICE_DEVICE_CONFIG, \"ConfigurationFinished\", {\"NewStatus\": \"ChangesApplied\"})\n\n self.config_started = not success\n return success"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef allow_block_device(self, mac_addr, device_status=BLOCK):\n _LOGGER.info(\"Allow block device\")\n if self.config_started:\n _LOGGER.error(\"Inconsistant configuration state, configuration already started\")\n return False\n\n if not self.config_start():\n _LOGGER.error(\"Could not start configuration\")\n return False\n\n success, _ = self._make_request(\n SERVICE_DEVICE_CONFIG, \"SetBlockDeviceByMAC\",\n {\"NewAllowOrBlock\": device_status, \"NewMACAddress\": mac_addr})\n\n if not success:\n _LOGGER.error(\"Could not successfully call allow/block device\")\n return False\n\n if not self.config_finish():\n _LOGGER.error(\"Inconsistant configuration state, configuration already finished\")\n return False\n\n return True", "response": "Allow or Block a device via its Mac Address."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nmake an API request to the router.", "response": "def _make_request(self, service, method, params=None, body=\"\",\n need_auth=True):\n \"\"\"Make an API request to the router.\"\"\"\n # If we have no cookie (v2) or never called login before (v1)\n # and we need auth, the request will fail for sure.\n if need_auth and not self.cookie:\n if not self.login():\n return False, None\n\n headers = self._get_headers(service, method, need_auth)\n\n if not body:\n if not params:\n params = \"\"\n if isinstance(params, dict):\n _map = params\n params = \"\"\n for k in _map:\n params += \"<\" + k + \">\" + _map[k] + \"\" + k + \">\\n\"\n\n body = CALL_BODY.format(service=SERVICE_PREFIX + service,\n method=method, params=params)\n\n message = SOAP_REQUEST.format(session_id=SESSION_ID, body=body)\n\n try:\n response = requests.post(self.soap_url, headers=headers,\n data=message, timeout=30, verify=False)\n\n if need_auth and _is_unauthorized_response(response):\n # let's discard the cookie because it probably expired (v2)\n # or the IP-bound (?) session expired (v1)\n self.cookie = None\n\n _LOGGER.warning(\"Unauthorized response, let's login and retry...\")\n if self.login():\n # reset headers with new cookie first\n headers = self._get_headers(service, method, need_auth)\n response = requests.post(self.soap_url, headers=headers,\n data=message, timeout=30, verify=False)\n\n success = _is_valid_response(response)\n\n if not success:\n _LOGGER.error(\"Invalid response\")\n _LOGGER.debug(\"%s\\n%s\\n%s\", response.status_code, str(response.headers), response.text)\n\n return success, response\n\n except requests.exceptions.RequestException:\n _LOGGER.exception(\"Error talking to API\")\n\n # Maybe one day we will distinguish between\n # different errors..\n return False, None"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef ip2long(ip):\n try:\n return int(binascii.hexlify(socket.inet_aton(ip)), 16)\n except socket.error:\n return int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, ip)), 16)", "response": "Wrapper function for IPv4 and IPv6 converters."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nconvert bytes data to file handle object.", "response": "def str2fp(data):\n \"\"\"\n Convert bytes data to file handle object (StringIO or BytesIO).\n\n :arg data: String data to transform\n \"\"\"\n return BytesIO(bytearray(data, const.ENCODING)) if const.PY3 else StringIO(data)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nparse the database file to determine what kind of database is and setup the internal internal", "response": "def _setup_segments(self):\n \"\"\"\n Parses the database file to determine what kind of database is\n being used and setup segment sizes and start points that will\n be used by the seek*() methods later.\n \"\"\"\n self._databaseType = const.COUNTRY_EDITION\n self._recordLength = const.STANDARD_RECORD_LENGTH\n self._databaseSegments = const.COUNTRY_BEGIN\n\n filepos = self._fp.tell()\n self._fp.seek(-3, os.SEEK_END)\n\n for i in range(const.STRUCTURE_INFO_MAX_SIZE):\n chars = chr(255) * 3\n delim = self._fp.read(3)\n\n if PY3 and type(delim) is bytes:\n delim = delim.decode(ENCODING)\n\n if PY2:\n chars = chars.decode(ENCODING)\n if type(delim) is str:\n delim = delim.decode(ENCODING)\n\n if delim == chars:\n byte = self._fp.read(1)\n self._databaseType = ord(byte)\n\n # Compatibility with databases from April 2003 and earlier\n if self._databaseType >= 106:\n self._databaseType -= 105\n\n if self._databaseType == const.REGION_EDITION_REV0:\n self._databaseSegments = const.STATE_BEGIN_REV0\n\n elif self._databaseType == const.REGION_EDITION_REV1:\n self._databaseSegments = const.STATE_BEGIN_REV1\n\n elif self._databaseType in (const.CITY_EDITION_REV0,\n const.CITY_EDITION_REV1,\n const.CITY_EDITION_REV1_V6,\n const.ORG_EDITION,\n const.ISP_EDITION,\n const.NETSPEED_EDITION_REV1,\n const.NETSPEED_EDITION_REV1_V6,\n const.ASNUM_EDITION,\n const.ASNUM_EDITION_V6):\n self._databaseSegments = 0\n buf = self._fp.read(const.SEGMENT_RECORD_LENGTH)\n\n if PY3 and type(buf) is bytes:\n buf = buf.decode(ENCODING)\n\n for j in range(const.SEGMENT_RECORD_LENGTH):\n self._databaseSegments += (ord(buf[j]) << (j * 8))\n\n LONG_RECORDS = (const.ORG_EDITION, const.ISP_EDITION)\n if self._databaseType in LONG_RECORDS:\n self._recordLength = const.ORG_RECORD_LENGTH\n break\n else:\n self._fp.seek(-4, os.SEEK_CUR)\n\n self._fp.seek(filepos, os.SEEK_SET)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nseek to the record that corresponds to the given IP address integer.", "response": "def _seek_country(self, ipnum):\n \"\"\"\n Using the record length and appropriate start points, seek to the\n country that corresponds to the converted IP address integer.\n Return offset of record.\n\n :arg ipnum: Result of ip2long conversion\n \"\"\"\n try:\n offset = 0\n seek_depth = 127 if len(str(ipnum)) > 10 else 31\n\n for depth in range(seek_depth, -1, -1):\n if self._flags & const.MEMORY_CACHE:\n startIndex = 2 * self._recordLength * offset\n endIndex = startIndex + (2 * self._recordLength)\n buf = self._memory[startIndex:endIndex]\n else:\n startIndex = 2 * self._recordLength * offset\n readLength = 2 * self._recordLength\n try:\n self._lock.acquire()\n self._fp.seek(startIndex, os.SEEK_SET)\n buf = self._fp.read(readLength)\n finally:\n self._lock.release()\n\n if PY3 and type(buf) is bytes:\n buf = buf.decode(ENCODING)\n\n x = [0, 0]\n for i in range(2):\n for j in range(self._recordLength):\n byte = buf[self._recordLength * i + j]\n x[i] += ord(byte) << (j * 8)\n if ipnum & (1 << depth):\n if x[1] >= self._databaseSegments:\n self._netmask = seek_depth - depth + 1\n return x[1]\n offset = x[1]\n else:\n if x[0] >= self._databaseSegments:\n self._netmask = seek_depth - depth + 1\n return x[0]\n offset = x[0]\n except (IndexError, UnicodeDecodeError):\n pass\n\n raise GeoIPError('Corrupt database')"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nget org name for ipnum.", "response": "def _get_org(self, ipnum):\n \"\"\"\n Seek and return organization or ISP name for ipnum.\n Return org/isp name.\n\n :arg ipnum: Result of ip2long conversion\n \"\"\"\n seek_org = self._seek_country(ipnum)\n if seek_org == self._databaseSegments:\n return None\n\n read_length = (2 * self._recordLength - 1) * self._databaseSegments\n try:\n self._lock.acquire()\n self._fp.seek(seek_org + read_length, os.SEEK_SET)\n buf = self._fp.read(const.MAX_ORG_RECORD_LENGTH)\n finally:\n self._lock.release()\n\n if PY3 and type(buf) is bytes:\n buf = buf.decode(ENCODING)\n\n return buf[:buf.index(chr(0))]"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns the region information for the given IP number.", "response": "def _get_region(self, ipnum):\n \"\"\"\n Seek and return the region information.\n Returns dict containing country_code and region_code.\n\n :arg ipnum: Result of ip2long conversion\n \"\"\"\n region_code = None\n country_code = None\n seek_country = self._seek_country(ipnum)\n\n def get_region_code(offset):\n region1 = chr(offset // 26 + 65)\n region2 = chr(offset % 26 + 65)\n return ''.join([region1, region2])\n\n if self._databaseType == const.REGION_EDITION_REV0:\n seek_region = seek_country - const.STATE_BEGIN_REV0\n if seek_region >= 1000:\n country_code = 'US'\n region_code = get_region_code(seek_region - 1000)\n else:\n country_code = const.COUNTRY_CODES[seek_region]\n elif self._databaseType == const.REGION_EDITION_REV1:\n seek_region = seek_country - const.STATE_BEGIN_REV1\n if seek_region < const.US_OFFSET:\n pass\n elif seek_region < const.CANADA_OFFSET:\n country_code = 'US'\n region_code = get_region_code(seek_region - const.US_OFFSET)\n elif seek_region < const.WORLD_OFFSET:\n country_code = 'CA'\n region_code = get_region_code(seek_region - const.CANADA_OFFSET)\n else:\n index = (seek_region - const.WORLD_OFFSET) // const.FIPS_RANGE\n if index < len(const.COUNTRY_CODES):\n country_code = const.COUNTRY_CODES[index]\n elif self._databaseType in const.CITY_EDITIONS:\n rec = self._get_record(ipnum)\n region_code = rec.get('region_code')\n country_code = rec.get('country_code')\n\n return {'country_code': country_code, 'region_code': region_code}"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _get_record(self, ipnum):\n seek_country = self._seek_country(ipnum)\n if seek_country == self._databaseSegments:\n return {}\n\n read_length = (2 * self._recordLength - 1) * self._databaseSegments\n try:\n self._lock.acquire()\n self._fp.seek(seek_country + read_length, os.SEEK_SET)\n buf = self._fp.read(const.FULL_RECORD_LENGTH)\n finally:\n self._lock.release()\n\n if PY3 and type(buf) is bytes:\n buf = buf.decode(ENCODING)\n\n record = {\n 'dma_code': 0,\n 'area_code': 0,\n 'metro_code': None,\n 'postal_code': None\n }\n\n latitude = 0\n longitude = 0\n\n char = ord(buf[0])\n record['country_code'] = const.COUNTRY_CODES[char]\n record['country_code3'] = const.COUNTRY_CODES3[char]\n record['country_name'] = const.COUNTRY_NAMES[char]\n record['continent'] = const.CONTINENT_NAMES[char]\n\n def read_data(buf, pos):\n cur = pos\n while buf[cur] != '\\0':\n cur += 1\n return cur, buf[pos:cur] if cur > pos else None\n\n offset, record['region_code'] = read_data(buf, 1)\n offset, record['city'] = read_data(buf, offset + 1)\n offset, record['postal_code'] = read_data(buf, offset + 1)\n offset = offset + 1\n\n for j in range(3):\n latitude += (ord(buf[offset + j]) << (j * 8))\n\n for j in range(3):\n longitude += (ord(buf[offset + j + 3]) << (j * 8))\n\n record['latitude'] = (latitude / 10000.0) - 180.0\n record['longitude'] = (longitude / 10000.0) - 180.0\n\n if self._databaseType in (const.CITY_EDITION_REV1, const.CITY_EDITION_REV1_V6):\n if record['country_code'] == 'US':\n dma_area = 0\n for j in range(3):\n dma_area += ord(buf[offset + j + 6]) << (j * 8)\n\n record['dma_code'] = int(floor(dma_area / 1000))\n record['area_code'] = dma_area % 1000\n record['metro_code'] = const.DMA_MAP.get(record['dma_code'])\n\n params = (record['country_code'], record['region_code'])\n record['time_zone'] = time_zone_by_country_and_region(*params)\n\n return record", "response": "Reads a record from the file and returns a dict with numerous location properties."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _gethostbyname(self, hostname):\n if self._databaseType in const.IPV6_EDITIONS:\n response = socket.getaddrinfo(hostname, 0, socket.AF_INET6)\n family, socktype, proto, canonname, sockaddr = response[0]\n address, port, flow, scope = sockaddr\n return address\n else:\n return socket.gethostbyname(hostname)", "response": "Returns a hostname or None if hostname is not valid."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the database ID for the specified hostname.", "response": "def id_by_name(self, hostname):\n \"\"\"\n Returns the database ID for specified hostname.\n The id might be useful as array index. 0 is unknown.\n\n :arg hostname: Hostname to get ID from.\n \"\"\"\n addr = self._gethostbyname(hostname)\n return self.id_by_addr(addr)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the database ID for the specified address.", "response": "def id_by_addr(self, addr):\n \"\"\"\n Returns the database ID for specified address.\n The ID might be useful as array index. 0 is unknown.\n\n :arg addr: IPv4 or IPv6 address (eg. 203.0.113.30)\n \"\"\"\n if self._databaseType in (const.PROXY_EDITION, const.NETSPEED_EDITION_REV1, const.NETSPEED_EDITION_REV1_V6):\n raise GeoIPError('Invalid database type; this database is not supported')\n ipv = 6 if addr.find(':') >= 0 else 4\n if ipv == 4 and self._databaseType not in (const.COUNTRY_EDITION, const.NETSPEED_EDITION):\n raise GeoIPError('Invalid database type; this database supports IPv6 addresses, not IPv4')\n if ipv == 6 and self._databaseType != const.COUNTRY_EDITION_V6:\n raise GeoIPError('Invalid database type; this database supports IPv4 addresses, not IPv6')\n\n ipnum = util.ip2long(addr)\n return self._seek_country(ipnum) - const.COUNTRY_BEGIN"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning 2 - letter country code from IP address.", "response": "def country_code_by_addr(self, addr):\n \"\"\"\n Returns 2-letter country code (e.g. US) from IP address.\n\n :arg addr: IP address (e.g. 203.0.113.30)\n \"\"\"\n VALID_EDITIONS = (const.COUNTRY_EDITION, const.COUNTRY_EDITION_V6)\n if self._databaseType in VALID_EDITIONS:\n country_id = self.id_by_addr(addr)\n return const.COUNTRY_CODES[country_id]\n elif self._databaseType in const.REGION_CITY_EDITIONS:\n return self.region_by_addr(addr).get('country_code')\n\n raise GeoIPError('Invalid database type, expected Country, City or Region')"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef country_code_by_name(self, hostname):\n addr = self._gethostbyname(hostname)\n return self.country_code_by_addr(addr)", "response": "Returns 2 - letter country code from hostname."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef netspeed_by_addr(self, addr):\n if self._databaseType == const.NETSPEED_EDITION:\n return const.NETSPEED_NAMES[self.id_by_addr(addr)]\n elif self._databaseType in (const.NETSPEED_EDITION_REV1,\n const.NETSPEED_EDITION_REV1_V6):\n ipnum = util.ip2long(addr)\n return self._get_org(ipnum)\n\n raise GeoIPError(\n 'Invalid database type, expected NetSpeed or NetSpeedCell')", "response": "Returns NetSpeed name from address."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns NetSpeed name from hostname. Can be Unknown Dial - up Cable Corporate.", "response": "def netspeed_by_name(self, hostname):\n \"\"\"\n Returns NetSpeed name from hostname. Can be Unknown, Dial-up,\n Cable, or Corporate.\n\n :arg hostname: Hostname (e.g. example.com)\n \"\"\"\n addr = self._gethostbyname(hostname)\n return self.netspeed_by_addr(addr)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef country_name_by_addr(self, addr):\n VALID_EDITIONS = (const.COUNTRY_EDITION, const.COUNTRY_EDITION_V6)\n if self._databaseType in VALID_EDITIONS:\n country_id = self.id_by_addr(addr)\n return const.COUNTRY_NAMES[country_id]\n elif self._databaseType in const.CITY_EDITIONS:\n return self.record_by_addr(addr).get('country_name')\n else:\n message = 'Invalid database type, expected Country or City'\n raise GeoIPError(message)", "response": "Returns the full country name for the specified IP address."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the full country name for the specified hostname.", "response": "def country_name_by_name(self, hostname):\n \"\"\"\n Returns full country name for specified hostname.\n\n :arg hostname: Hostname (e.g. example.com)\n \"\"\"\n addr = self._gethostbyname(hostname)\n return self.country_name_by_addr(addr)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns the org name for given IP address.", "response": "def org_by_addr(self, addr):\n \"\"\"\n Returns Organization, ISP, or ASNum name for given IP address.\n\n :arg addr: IP address (e.g. 203.0.113.30)\n \"\"\"\n valid = (const.ORG_EDITION, const.ISP_EDITION,\n const.ASNUM_EDITION, const.ASNUM_EDITION_V6)\n if self._databaseType not in valid:\n message = 'Invalid database type, expected Org, ISP or ASNum'\n raise GeoIPError(message)\n\n ipnum = util.ip2long(addr)\n return self._get_org(ipnum)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef org_by_name(self, hostname):\n addr = self._gethostbyname(hostname)\n return self.org_by_addr(addr)", "response": "Returns Organization ISP or ASNum name for given hostname."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef record_by_addr(self, addr):\n if self._databaseType not in const.CITY_EDITIONS:\n message = 'Invalid database type, expected City'\n raise GeoIPError(message)\n\n ipnum = util.ip2long(addr)\n rec = self._get_record(ipnum)\n if not rec:\n return None\n\n return rec", "response": "Returns a dictionary with city data containing the given IP address."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef record_by_name(self, hostname):\n addr = self._gethostbyname(hostname)\n return self.record_by_addr(addr)", "response": "Returns a dictionary with city data containing the given hostname."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a dictionary containing country_code and region_code for the given IP address.", "response": "def region_by_addr(self, addr):\n \"\"\"\n Returns dictionary containing `country_code` and `region_code`.\n\n :arg addr: IP address (e.g. 203.0.113.30)\n \"\"\"\n if self._databaseType not in const.REGION_CITY_EDITIONS:\n message = 'Invalid database type, expected Region or City'\n raise GeoIPError(message)\n\n ipnum = util.ip2long(addr)\n return self._get_region(ipnum)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef region_by_name(self, hostname):\n addr = self._gethostbyname(hostname)\n return self.region_by_addr(addr)", "response": "Returns a dictionary containing country_code and region_code."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef time_zone_by_addr(self, addr):\n if self._databaseType not in const.CITY_EDITIONS:\n message = 'Invalid database type, expected City'\n raise GeoIPError(message)\n\n ipnum = util.ip2long(addr)\n return self._get_record(ipnum).get('time_zone')", "response": "Returns the time zone of the given IP address."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning a time zone in tzdata format by hostname.", "response": "def time_zone_by_name(self, hostname):\n \"\"\"\n Returns time zone in tzdata format (e.g. America/New_York or Europe/Paris)\n\n :arg hostname: Hostname (e.g. example.com)\n \"\"\"\n addr = self._gethostbyname(hostname)\n return self.time_zone_by_addr(addr)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the time zone of the given country and region code.", "response": "def time_zone_by_country_and_region(country_code, region_code=None):\n \"\"\"\n Returns time zone from country and region code.\n\n :arg country_code: Country code\n :arg region_code: Region code\n \"\"\"\n timezone = country_dict.get(country_code)\n if not timezone:\n return None\n\n if isinstance(timezone, str):\n return timezone\n\n return timezone.get(region_code)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef compress(self, filename):\n compressed_filename = self.get_compressed_filename(filename)\n if not compressed_filename:\n return\n\n self.do_compress(filename, compressed_filename)", "response": "Compress a file only if needed."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_compressed_filename(self, filename):\n if not os.path.splitext(filename)[1][1:] in self.suffixes_to_compress:\n return False\n\n file_stats = None\n compressed_stats = None\n compressed_filename = '{}.{}'.format(filename, self.suffix)\n try:\n file_stats = os.stat(filename)\n compressed_stats = os.stat(compressed_filename)\n except OSError: # FileNotFoundError is for Python3 only\n pass\n\n if file_stats and compressed_stats:\n return (compressed_filename\n if file_stats.st_mtime > compressed_stats.st_mtime\n else False)\n else:\n return compressed_filename", "response": "Returns the compressed filename."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef copy(src, dst, symlink=False, rellink=False):\n func = os.symlink if symlink else shutil.copy2\n if symlink and os.path.lexists(dst):\n os.remove(dst)\n if rellink: # relative symlink from dst\n func(os.path.relpath(src, os.path.dirname(dst)), dst)\n else:\n func(src, dst)", "response": "Copy or symlink the file."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef url_from_path(path):\n\n if os.sep != '/':\n path = '/'.join(path.split(os.sep))\n return quote(path)", "response": "Transform path to url converting backslashes to slashes if needed."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef read_markdown(filename):\n global MD\n # Use utf-8-sig codec to remove BOM if it is present. This is only possible\n # this way prior to feeding the text to the markdown parser (which would\n # also default to pure utf-8)\n with open(filename, 'r', encoding='utf-8-sig') as f:\n text = f.read()\n\n if MD is None:\n MD = Markdown(extensions=['markdown.extensions.meta',\n 'markdown.extensions.tables'],\n output_format='html5')\n else:\n MD.reset()\n # When https://github.com/Python-Markdown/markdown/pull/672\n # will be available, this can be removed.\n MD.Meta = {}\n\n # Mark HTML with Markup to prevent jinja2 autoescaping\n output = {'description': Markup(MD.convert(text))}\n\n try:\n meta = MD.Meta.copy()\n except AttributeError:\n pass\n else:\n output['meta'] = meta\n try:\n output['title'] = MD.Meta['title'][0]\n except KeyError:\n pass\n\n return output", "response": "Reads a markdown file converts output and fetches title and meta - data for possible\n further processing."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef load_exif(album):\n if not hasattr(album.gallery, \"exifCache\"):\n _restore_cache(album.gallery)\n cache = album.gallery.exifCache\n\n for media in album.medias:\n if media.type == \"image\":\n key = os.path.join(media.path, media.filename)\n if key in cache:\n media.exif = cache[key]", "response": "Loads the exif data of all images in an album from cache"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _restore_cache(gallery):\n cachePath = os.path.join(gallery.settings[\"destination\"], \".exif_cache\")\n try:\n if os.path.exists(cachePath):\n with open(cachePath, \"rb\") as cacheFile:\n gallery.exifCache = pickle.load(cacheFile)\n logger.debug(\"Loaded cache with %d entries\", len(gallery.exifCache))\n else:\n gallery.exifCache = {}\n except Exception as e:\n logger.warn(\"Could not load cache: %s\", e)\n gallery.exifCache = {}", "response": "Restores the exif data cache from the cache file"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef save_cache(gallery):\n\n if hasattr(gallery, \"exifCache\"):\n cache = gallery.exifCache\n else:\n cache = gallery.exifCache = {}\n\n for album in gallery.albums.values():\n for image in album.images:\n cache[os.path.join(image.path, image.filename)] = image.exif\n\n cachePath = os.path.join(gallery.settings[\"destination\"], \".exif_cache\")\n\n if len(cache) == 0:\n if os.path.exists(cachePath):\n os.remove(cachePath)\n return\n\n try:\n with open(cachePath, \"wb\") as cacheFile:\n pickle.dump(cache, cacheFile)\n logger.debug(\"Stored cache with %d entries\", len(gallery.exifCache))\n except Exception as e:\n logger.warn(\"Could not store cache: %s\", e)\n os.remove(cachePath)", "response": "Stores the exif data of all images in the gallery"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nremove all filtered Media and subdirs from an Album", "response": "def filter_nomedia(album, settings=None):\n \"\"\"Removes all filtered Media and subdirs from an Album\"\"\"\n nomediapath = os.path.join(album.src_path, \".nomedia\")\n\n if os.path.isfile(nomediapath):\n if os.path.getsize(nomediapath) == 0:\n logger.info(\"Ignoring album '%s' because of present 0-byte \"\n \".nomedia file\", album.name)\n\n # subdirs have been added to the gallery already, remove them\n # there, too\n _remove_albums_with_subdirs(album.gallery.albums, [album.path])\n try:\n os.rmdir(album.dst_path)\n except OSError as e:\n # directory was created and populated with images in a\n # previous run => keep it\n pass\n\n # cannot set albums => empty subdirs so that no albums are\n # generated\n album.subdirs = []\n album.medias = []\n\n else:\n with open(nomediapath, \"r\") as nomediaFile:\n logger.info(\"Found a .nomedia file in %s, ignoring its \"\n \"entries\", album.name)\n ignored = nomediaFile.read().split(\"\\n\")\n\n album.medias = [media for media in album.medias\n if media.src_filename not in ignored]\n album.subdirs = [dirname for dirname in album.subdirs\n if dirname not in ignored]\n\n # subdirs have been added to the gallery already, remove\n # them there, too\n _remove_albums_with_subdirs(album.gallery.albums,\n ignored, album.path + os.path.sep)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncreate a new sample config file in the current directory.", "response": "def init(path):\n \"\"\"Copy a sample config file in the current directory (default to\n 'sigal.conf.py'), or use the provided 'path'.\"\"\"\n\n if os.path.isfile(path):\n print(\"Found an existing config file, will abort to keep it safe.\")\n sys.exit(1)\n\n from pkg_resources import resource_string\n conf = resource_string(__name__, 'templates/sigal.conf.py')\n\n with open(path, 'w', encoding='utf-8') as f:\n f.write(conf.decode('utf8'))\n print(\"Sample config file created: {}\".format(path))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nbuild a new image from a source directory and destination directory.", "response": "def build(source, destination, debug, verbose, force, config, theme, title,\n ncpu):\n \"\"\"Run sigal to process a directory.\n\n If provided, 'source', 'destination' and 'theme' will override the\n corresponding values from the settings file.\n\n \"\"\"\n level = ((debug and logging.DEBUG) or (verbose and logging.INFO) or\n logging.WARNING)\n init_logging(__name__, level=level)\n logger = logging.getLogger(__name__)\n\n if not os.path.isfile(config):\n logger.error(\"Settings file not found: %s\", config)\n sys.exit(1)\n\n start_time = time.time()\n settings = read_settings(config)\n\n for key in ('source', 'destination', 'theme'):\n arg = locals()[key]\n if arg is not None:\n settings[key] = os.path.abspath(arg)\n logger.info(\"%12s : %s\", key.capitalize(), settings[key])\n\n if not settings['source'] or not os.path.isdir(settings['source']):\n logger.error(\"Input directory not found: %s\", settings['source'])\n sys.exit(1)\n\n # on windows os.path.relpath raises a ValueError if the two paths are on\n # different drives, in that case we just ignore the exception as the two\n # paths are anyway not relative\n relative_check = True\n try:\n relative_check = os.path.relpath(settings['destination'],\n settings['source']).startswith('..')\n except ValueError:\n pass\n\n if not relative_check:\n logger.error(\"Output directory should be outside of the input \"\n \"directory.\")\n sys.exit(1)\n\n if title:\n settings['title'] = title\n\n locale.setlocale(locale.LC_ALL, settings['locale'])\n init_plugins(settings)\n\n gal = Gallery(settings, ncpu=ncpu)\n gal.build(force=force)\n\n # copy extra files\n for src, dst in settings['files_to_copy']:\n src = os.path.join(settings['source'], src)\n dst = os.path.join(settings['destination'], dst)\n logger.debug('Copy %s to %s', src, dst)\n copy(src, dst, symlink=settings['orig_link'], rellink=settings['rel_link'])\n\n stats = gal.stats\n\n def format_stats(_type):\n opt = [\"{} {}\".format(stats[_type + '_' + subtype], subtype)\n for subtype in ('skipped', 'failed')\n if stats[_type + '_' + subtype] > 0]\n opt = ' ({})'.format(', '.join(opt)) if opt else ''\n return '{} {}s{}'.format(stats[_type], _type, opt)\n\n print('Done.\\nProcessed {} and {} in {:.2f} seconds.'\n .format(format_stats('image'), format_stats('video'),\n time.time() - start_time))"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef init_plugins(settings):\n\n logger = logging.getLogger(__name__)\n logger.debug('Plugin paths: %s', settings['plugin_paths'])\n\n for path in settings['plugin_paths']:\n sys.path.insert(0, path)\n\n for plugin in settings['plugins']:\n try:\n if isinstance(plugin, str):\n mod = importlib.import_module(plugin)\n mod.register(settings)\n else:\n plugin.register(settings)\n logger.debug('Registered plugin %s', plugin)\n except Exception as e:\n logger.error('Failed to load plugin %s: %r', plugin, e)\n\n for path in settings['plugin_paths']:\n sys.path.remove(path)", "response": "Load plugins and call register method."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef serve(destination, port, config):\n if os.path.exists(destination):\n pass\n elif os.path.exists(config):\n settings = read_settings(config)\n destination = settings.get('destination')\n if not os.path.exists(destination):\n sys.stderr.write(\"The '{}' directory doesn't exist, maybe try \"\n \"building first?\\n\".format(destination))\n sys.exit(1)\n else:\n sys.stderr.write(\"The {destination} directory doesn't exist \"\n \"and the config file ({config}) could not be read.\\n\"\n .format(destination=destination, config=config))\n sys.exit(2)\n\n print('DESTINATION : {}'.format(destination))\n os.chdir(destination)\n Handler = server.SimpleHTTPRequestHandler\n httpd = socketserver.TCPServer((\"\", port), Handler, False)\n print(\" * Running on http://127.0.0.1:{}/\".format(port))\n\n try:\n httpd.allow_reuse_address = True\n httpd.server_bind()\n httpd.server_activate()\n httpd.serve_forever()\n except KeyboardInterrupt:\n print('\\nAll done!')", "response": "Run a simple web server."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef set_meta(target, keys, overwrite=False):\n\n if not os.path.exists(target):\n sys.stderr.write(\"The target {} does not exist.\\n\".format(target))\n sys.exit(1)\n if len(keys) < 2 or len(keys) % 2 > 0:\n sys.stderr.write(\"Need an even number of arguments.\\n\")\n sys.exit(1)\n\n if os.path.isdir(target):\n descfile = os.path.join(target, 'index.md')\n else:\n descfile = os.path.splitext(target)[0] + '.md'\n if os.path.exists(descfile) and not overwrite:\n sys.stderr.write(\"Description file '{}' already exists. \"\n \"Use --overwrite to overwrite it.\\n\".format(descfile))\n sys.exit(2)\n\n with open(descfile, \"w\") as fp:\n for i in range(len(keys) // 2):\n k, v = keys[i * 2:(i + 1) * 2]\n fp.write(\"{}: {}\\n\".format(k.capitalize(), v))\n print(\"{} metadata key(s) written to {}\".format(len(keys) // 2, descfile))", "response": "Write metadata keys to. md file."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngenerating an image from a source file.", "response": "def generate_image(source, outname, settings, options=None):\n \"\"\"Image processor, rotate and resize the image.\n\n :param source: path to an image\n :param outname: output filename\n :param settings: settings dict\n :param options: dict with PIL options (quality, optimize, progressive)\n\n \"\"\"\n\n logger = logging.getLogger(__name__)\n\n if settings['use_orig'] or source.endswith('.gif'):\n utils.copy(source, outname, symlink=settings['orig_link'])\n return\n\n img = _read_image(source)\n original_format = img.format\n\n if settings['copy_exif_data'] and settings['autorotate_images']:\n logger.warning(\"The 'autorotate_images' and 'copy_exif_data' settings \"\n \"are not compatible because Sigal can't save the \"\n \"modified Orientation tag.\")\n\n # Preserve EXIF data\n if settings['copy_exif_data'] and _has_exif_tags(img):\n if options is not None:\n options = deepcopy(options)\n else:\n options = {}\n options['exif'] = img.info['exif']\n\n # Rotate the img, and catch IOError when PIL fails to read EXIF\n if settings['autorotate_images']:\n try:\n img = Transpose().process(img)\n except (IOError, IndexError):\n pass\n\n # Resize the image\n if settings['img_processor']:\n try:\n logger.debug('Processor: %s', settings['img_processor'])\n processor_cls = getattr(pilkit.processors,\n settings['img_processor'])\n except AttributeError:\n logger.error('Wrong processor name: %s', settings['img_processor'])\n sys.exit()\n\n width, height = settings['img_size']\n\n if img.size[0] < img.size[1]:\n # swap target size if image is in portrait mode\n height, width = width, height\n\n processor = processor_cls(width, height, upscale=False)\n img = processor.process(img)\n\n # signal.send() does not work here as plugins can modify the image, so we\n # iterate other the receivers to call them with the image.\n for receiver in signals.img_resized.receivers_for(img):\n img = receiver(img, settings=settings)\n\n outformat = img.format or original_format or 'JPEG'\n logger.debug('Save resized image to %s (%s)', outname, outformat)\n save_image(img, outname, outformat, options=options, autoconvert=True)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef generate_thumbnail(source, outname, box, fit=True, options=None,\n thumb_fit_centering=(0.5, 0.5)):\n \"\"\"Create a thumbnail image.\"\"\"\n\n logger = logging.getLogger(__name__)\n img = _read_image(source)\n original_format = img.format\n\n if fit:\n img = ImageOps.fit(img, box, PILImage.ANTIALIAS,\n centering=thumb_fit_centering)\n else:\n img.thumbnail(box, PILImage.ANTIALIAS)\n\n outformat = img.format or original_format or 'JPEG'\n logger.debug('Save thumnail image: %s (%s)', outname, outformat)\n save_image(img, outname, outformat, options=options, autoconvert=True)", "response": "Generate a thumbnail image."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nprocesses one image resize create thumbnail", "response": "def process_image(filepath, outpath, settings):\n \"\"\"Process one image: resize, create thumbnail.\"\"\"\n\n logger = logging.getLogger(__name__)\n logger.info('Processing %s', filepath)\n filename = os.path.split(filepath)[1]\n outname = os.path.join(outpath, filename)\n ext = os.path.splitext(filename)[1]\n\n if ext in ('.jpg', '.jpeg', '.JPG', '.JPEG'):\n options = settings['jpg_options']\n elif ext == '.png':\n options = {'optimize': True}\n else:\n options = {}\n\n try:\n generate_image(filepath, outname, settings, options=options)\n\n if settings['make_thumbs']:\n thumb_name = os.path.join(outpath, get_thumb(settings, filename))\n generate_thumbnail(\n outname, thumb_name, settings['thumb_size'],\n fit=settings['thumb_fit'], options=options,\n thumb_fit_centering=settings[\"thumb_fit_centering\"])\n except Exception as e:\n logger.info('Failed to process: %r', e)\n if logger.getEffectiveLevel() == logging.DEBUG:\n raise\n else:\n return Status.FAILURE\n\n return Status.SUCCESS"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef get_size(file_path):\n try:\n im = _read_image(file_path)\n except (IOError, IndexError, TypeError, AttributeError) as e:\n logger = logging.getLogger(__name__)\n logger.error(\"Could not read size of %s due to %r\", file_path, e)\n else:\n width, height = im.size\n return {\n 'width': width,\n 'height': height\n }", "response": "Return image size ( width and height"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get_exif_data(filename):\n\n logger = logging.getLogger(__name__)\n\n img = _read_image(filename)\n\n try:\n exif = img._getexif() or {}\n except ZeroDivisionError:\n logger.warning('Failed to read EXIF data.')\n return None\n\n data = {TAGS.get(tag, tag): value for tag, value in exif.items()}\n\n if 'GPSInfo' in data:\n try:\n data['GPSInfo'] = {GPSTAGS.get(tag, tag): value\n for tag, value in data['GPSInfo'].items()}\n except AttributeError:\n logger = logging.getLogger(__name__)\n logger.info('Failed to get GPS Info')\n del data['GPSInfo']\n return data", "response": "Return a dict with the raw EXIF data."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns a dict with the raw IPTC data.", "response": "def get_iptc_data(filename):\n \"\"\"Return a dict with the raw IPTC data.\"\"\"\n\n logger = logging.getLogger(__name__)\n\n iptc_data = {}\n raw_iptc = {}\n\n # PILs IptcImagePlugin issues a SyntaxError in certain circumstances\n # with malformed metadata, see PIL/IptcImagePlugin.py\", line 71.\n # ( https://github.com/python-pillow/Pillow/blob/9dd0348be2751beb2c617e32ff9985aa2f92ae5f/src/PIL/IptcImagePlugin.py#L71 )\n try:\n img = _read_image(filename)\n raw_iptc = IptcImagePlugin.getiptcinfo(img)\n except SyntaxError:\n logger.info('IPTC Error in %s', filename)\n\n # IPTC fields are catalogued in:\n # https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata\n # 2:05 is the IPTC title property\n if raw_iptc and (2, 5) in raw_iptc:\n iptc_data[\"title\"] = raw_iptc[(2, 5)].decode('utf-8', errors='replace')\n\n # 2:120 is the IPTC description property\n if raw_iptc and (2, 120) in raw_iptc:\n iptc_data[\"description\"] = raw_iptc[(2, 120)].decode('utf-8',\n errors='replace')\n\n # 2:105 is the IPTC headline property\n if raw_iptc and (2, 105) in raw_iptc:\n iptc_data[\"headline\"] = raw_iptc[(2, 105)].decode('utf-8',\n errors='replace')\n\n return iptc_data"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef dms_to_degrees(v):\n\n d = float(v[0][0]) / float(v[0][1])\n m = float(v[1][0]) / float(v[1][1])\n s = float(v[2][0]) / float(v[2][1])\n return d + (m / 60.0) + (s / 3600.0)", "response": "Convert degree minute second to decimal degrees."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_exif_tags(data, datetime_format='%c'):\n\n logger = logging.getLogger(__name__)\n simple = {}\n\n for tag in ('Model', 'Make', 'LensModel'):\n if tag in data:\n if isinstance(data[tag], tuple):\n simple[tag] = data[tag][0].strip()\n else:\n simple[tag] = data[tag].strip()\n\n if 'FNumber' in data:\n fnumber = data['FNumber']\n try:\n simple['fstop'] = float(fnumber[0]) / fnumber[1]\n except Exception:\n logger.debug('Skipped invalid FNumber: %r', fnumber, exc_info=True)\n\n if 'FocalLength' in data:\n focal = data['FocalLength']\n try:\n simple['focal'] = round(float(focal[0]) / focal[1])\n except Exception:\n logger.debug('Skipped invalid FocalLength: %r', focal,\n exc_info=True)\n\n if 'ExposureTime' in data:\n exptime = data['ExposureTime']\n if isinstance(exptime, tuple):\n try:\n simple['exposure'] = str(fractions.Fraction(exptime[0],\n exptime[1]))\n except ZeroDivisionError:\n logger.info('Invalid ExposureTime: %r', exptime)\n elif isinstance(exptime, int):\n simple['exposure'] = str(exptime)\n else:\n logger.info('Unknown format for ExposureTime: %r', exptime)\n\n if data.get('ISOSpeedRatings'):\n simple['iso'] = data['ISOSpeedRatings']\n\n if 'DateTimeOriginal' in data:\n # Remove null bytes at the end if necessary\n date = data['DateTimeOriginal'].rsplit('\\x00')[0]\n\n try:\n simple['dateobj'] = datetime.strptime(date, '%Y:%m:%d %H:%M:%S')\n simple['datetime'] = simple['dateobj'].strftime(datetime_format)\n except (ValueError, TypeError) as e:\n logger.info('Could not parse DateTimeOriginal: %s', e)\n\n if 'GPSInfo' in data:\n info = data['GPSInfo']\n lat_info = info.get('GPSLatitude')\n lon_info = info.get('GPSLongitude')\n lat_ref_info = info.get('GPSLatitudeRef')\n lon_ref_info = info.get('GPSLongitudeRef')\n\n if lat_info and lon_info and lat_ref_info and lon_ref_info:\n try:\n lat = dms_to_degrees(lat_info)\n lon = dms_to_degrees(lon_info)\n except (ZeroDivisionError, ValueError, TypeError):\n logger.info('Failed to read GPS info')\n else:\n simple['gps'] = {\n 'lat': - lat if lat_ref_info != 'N' else lat,\n 'lon': - lon if lon_ref_info != 'E' else lon,\n }\n\n return simple", "response": "Make a simplified version with common tags from raw EXIF data."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef big(self):\n if self.settings['keep_orig']:\n s = self.settings\n if s['use_orig']:\n # The image *is* the original, just use it\n return self.filename\n orig_path = join(s['destination'], self.path, s['orig_dir'])\n check_or_create_dir(orig_path)\n big_path = join(orig_path, self.src_filename)\n if not isfile(big_path):\n copy(self.src_path, big_path, symlink=s['orig_link'],\n rellink=self.settings['rel_link'])\n return join(s['orig_dir'], self.src_filename)", "response": "Path to the original image."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef thumbnail(self):\n\n if not isfile(self.thumb_path):\n self.logger.debug('Generating thumbnail for %r', self)\n path = (self.dst_path if os.path.exists(self.dst_path)\n else self.src_path)\n try:\n # if thumbnail is missing (if settings['make_thumbs'] is False)\n s = self.settings\n if self.type == 'image':\n image.generate_thumbnail(\n path, self.thumb_path, s['thumb_size'],\n fit=s['thumb_fit'])\n elif self.type == 'video':\n video.generate_thumbnail(\n path, self.thumb_path, s['thumb_size'],\n s['thumb_video_delay'], fit=s['thumb_fit'],\n converter=s['video_converter'])\n except Exception as e:\n self.logger.error('Failed to generate thumbnail: %s', e)\n return\n return url_from_path(self.thumb_name)", "response": "Returns the path to the thumbnail image."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _get_metadata(self):\n self.description = ''\n self.meta = {}\n self.title = ''\n\n descfile = splitext(self.src_path)[0] + '.md'\n if isfile(descfile):\n meta = read_markdown(descfile)\n for key, val in meta.items():\n setattr(self, key, val)", "response": "Get image metadata from filename. md"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _get_metadata(self):\n descfile = join(self.src_path, self.description_file)\n self.description = ''\n self.meta = {}\n # default: get title from directory name\n self.title = os.path.basename(self.path if self.path != '.'\n else self.src_path)\n\n if isfile(descfile):\n meta = read_markdown(descfile)\n for key, val in meta.items():\n setattr(self, key, val)\n\n try:\n self.author = self.meta['author'][0]\n except KeyError:\n self.author = self.settings.get('author')", "response": "Get album metadata from description_file."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncreate output directories for thumbnails and original images.", "response": "def create_output_directories(self):\n \"\"\"Create output directories for thumbnails and original images.\"\"\"\n check_or_create_dir(self.dst_path)\n\n if self.medias:\n check_or_create_dir(join(self.dst_path,\n self.settings['thumb_dir']))\n\n if self.medias and self.settings['keep_orig']:\n self.orig_path = join(self.dst_path, self.settings['orig_dir'])\n check_or_create_dir(self.orig_path)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nlist of albums for each unique ID.", "response": "def albums(self):\n \"\"\"List of :class:`~sigal.gallery.Album` objects for each\n sub-directory.\n \"\"\"\n root_path = self.path if self.path != '.' else ''\n return [self.gallery.albums[join(root_path, path)]\n for path in self.subdirs]"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef url(self):\n url = self.name.encode('utf-8')\n return url_quote(url) + '/' + self.url_ext", "response": "URL of the album relative to its parent."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef thumbnail(self):\n\n if self._thumbnail:\n # stop if it is already set\n return self._thumbnail\n\n # Test the thumbnail from the Markdown file.\n thumbnail = self.meta.get('thumbnail', [''])[0]\n\n if thumbnail and isfile(join(self.src_path, thumbnail)):\n self._thumbnail = url_from_path(join(\n self.name, get_thumb(self.settings, thumbnail)))\n self.logger.debug(\"Thumbnail for %r : %s\", self, self._thumbnail)\n return self._thumbnail\n else:\n # find and return the first landscape image\n for f in self.medias:\n ext = splitext(f.filename)[1]\n if ext.lower() in self.settings['img_extensions']:\n # Use f.size if available as it is quicker (in cache), but\n # fallback to the size of src_path if dst_path is missing\n size = f.size\n if size is None:\n size = get_size(f.src_path)\n\n if size['width'] > size['height']:\n self._thumbnail = (url_quote(self.name) + '/' +\n f.thumbnail)\n self.logger.debug(\n \"Use 1st landscape image as thumbnail for %r : %s\",\n self, self._thumbnail)\n return self._thumbnail\n\n # else simply return the 1st media file\n if not self._thumbnail and self.medias:\n for media in self.medias:\n if media.thumbnail is not None:\n self._thumbnail = (url_quote(self.name) + '/' +\n media.thumbnail)\n break\n else:\n self.logger.warning(\"No thumbnail found for %r\", self)\n return None\n\n self.logger.debug(\"Use the 1st image as thumbnail for %r : %s\",\n self, self._thumbnail)\n return self._thumbnail\n\n # use the thumbnail of their sub-directories\n if not self._thumbnail:\n for path, album in self.gallery.get_albums(self.path):\n if album.thumbnail:\n self._thumbnail = (url_quote(self.name) + '/' +\n album.thumbnail)\n self.logger.debug(\n \"Using thumbnail from sub-directory for %r : %s\",\n self, self._thumbnail)\n return self._thumbnail\n\n self.logger.error('Thumbnail not found for %r', self)\n return None", "response": "Return the path to the thumbnail of the album."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn a list of tuples defining the current breadcrumb.", "response": "def breadcrumb(self):\n \"\"\"List of ``(url, title)`` tuples defining the current breadcrumb\n path.\n \"\"\"\n if self.path == '.':\n return []\n\n path = self.path\n breadcrumb = [((self.url_ext or '.'), self.title)]\n\n while True:\n path = os.path.normpath(os.path.join(path, '..'))\n if path == '.':\n break\n\n url = (url_from_path(os.path.relpath(path, self.path)) + '/' +\n self.url_ext)\n breadcrumb.append((url, self.gallery.albums[path].title))\n\n breadcrumb.reverse()\n return breadcrumb"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef zip(self):\n zip_gallery = self.settings['zip_gallery']\n\n if zip_gallery and len(self) > 0:\n zip_gallery = zip_gallery.format(album=self)\n archive_path = join(self.dst_path, zip_gallery)\n if (self.settings.get('zip_skip_if_exists', False) and\n isfile(archive_path)):\n self.logger.debug(\"Archive %s already created, passing\",\n archive_path)\n return zip_gallery\n\n archive = zipfile.ZipFile(archive_path, 'w', allowZip64=True)\n attr = ('src_path' if self.settings['zip_media_format'] == 'orig'\n else 'dst_path')\n\n for p in self:\n path = getattr(p, attr)\n try:\n archive.write(path, os.path.split(path)[1])\n except OSError as e:\n self.logger.warn('Failed to add %s to the ZIP: %s', p, e)\n\n archive.close()\n self.logger.debug('Created ZIP archive %s', archive_path)\n return zip_gallery", "response": "Create a ZIP archive with all media files and return its path."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_albums(self, path):\n\n for name in self.albums[path].subdirs:\n subdir = os.path.normpath(join(path, name))\n yield subdir, self.albums[subdir]\n for subname, album in self.get_albums(subdir):\n yield subname, self.albums[subdir]", "response": "Return the list of all sub - directories of path and albums."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ncreates the image gallery", "response": "def build(self, force=False):\n \"Create the image gallery\"\n\n if not self.albums:\n self.logger.warning(\"No albums found.\")\n return\n\n def log_func(x):\n # 63 is the total length of progressbar, label, percentage, etc\n available_length = get_terminal_size()[0] - 64\n if x and available_length > 10:\n return x.name[:available_length]\n else:\n return \"\"\n\n try:\n with progressbar(self.albums.values(), label=\"Collecting files\",\n item_show_func=log_func, show_eta=False,\n file=self.progressbar_target) as albums:\n media_list = [f for album in albums\n for f in self.process_dir(album, force=force)]\n except KeyboardInterrupt:\n sys.exit('Interrupted')\n\n bar_opt = {'label': \"Processing files\",\n 'show_pos': True,\n 'file': self.progressbar_target}\n failed_files = []\n\n if self.pool:\n try:\n with progressbar(length=len(media_list), **bar_opt) as bar:\n for res in self.pool.imap_unordered(worker, media_list):\n if res:\n failed_files.append(res)\n bar.update(1)\n self.pool.close()\n self.pool.join()\n except KeyboardInterrupt:\n self.pool.terminate()\n sys.exit('Interrupted')\n except pickle.PicklingError:\n self.logger.critical(\n \"Failed to process files with the multiprocessing feature.\"\n \" This can be caused by some module import or object \"\n \"defined in the settings file, which can't be serialized.\",\n exc_info=True)\n sys.exit('Abort')\n else:\n with progressbar(media_list, **bar_opt) as medias:\n for media_item in medias:\n res = process_file(media_item)\n if res:\n failed_files.append(res)\n\n if failed_files:\n self.remove_files(failed_files)\n\n if self.settings['write_html']:\n album_writer = AlbumPageWriter(self.settings,\n index_title=self.title)\n album_list_writer = AlbumListPageWriter(self.settings,\n index_title=self.title)\n with progressbar(self.albums.values(),\n label=\"%16s\" % \"Writing files\",\n item_show_func=log_func, show_eta=False,\n file=self.progressbar_target) as albums:\n for album in albums:\n if album.albums:\n if album.medias:\n self.logger.warning(\n \"Album %s contains sub-albums and images. \"\n \"Please move images to their own sub-album. \"\n \"Images in album %s will not be visible.\",\n album.title, album.title\n )\n album_list_writer.write(album)\n else:\n album_writer.write(album)\n print('')\n\n signals.gallery_build.send(self)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nprocess a list of images in a directory.", "response": "def process_dir(self, album, force=False):\n \"\"\"Process a list of images in a directory.\"\"\"\n for f in album:\n if isfile(f.dst_path) and not force:\n self.logger.info(\"%s exists - skipping\", f.filename)\n self.stats[f.type + '_skipped'] += 1\n else:\n self.stats[f.type] += 1\n yield (f.type, f.path, f.filename, f.src_path, album.dst_path,\n self.settings)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn an image with reduced opacity.", "response": "def reduce_opacity(im, opacity):\n \"\"\"Returns an image with reduced opacity.\"\"\"\n assert opacity >= 0 and opacity <= 1\n if im.mode != 'RGBA':\n im = im.convert('RGBA')\n else:\n im = im.copy()\n alpha = im.split()[3]\n alpha = ImageEnhance.Brightness(alpha).enhance(opacity)\n im.putalpha(alpha)\n return im"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef watermark(im, mark, position, opacity=1):\n if opacity < 1:\n mark = reduce_opacity(mark, opacity)\n if im.mode != 'RGBA':\n im = im.convert('RGBA')\n # create a transparent layer the size of the image and draw the\n # watermark in that layer.\n layer = Image.new('RGBA', im.size, (0, 0, 0, 0))\n if position == 'tile':\n for y in range(0, im.size[1], mark.size[1]):\n for x in range(0, im.size[0], mark.size[0]):\n layer.paste(mark, (x, y))\n elif position == 'scale':\n # scale, but preserve the aspect ratio\n ratio = min(\n float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])\n w = int(mark.size[0] * ratio)\n h = int(mark.size[1] * ratio)\n mark = mark.resize((w, h))\n layer.paste(mark, (int((im.size[0] - w) / 2),\n int((im.size[1] - h) / 2)))\n else:\n layer.paste(mark, position)\n # composite the watermark with the layer\n return Image.composite(layer, im, layer)", "response": "Adds a watermark to an image."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef check_subprocess(cmd, source, outname):\n logger = logging.getLogger(__name__)\n try:\n res = subprocess.run(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n except KeyboardInterrupt:\n logger.debug('Process terminated, removing file %s', outname)\n if os.path.isfile(outname):\n os.remove(outname)\n raise\n\n if res.returncode:\n logger.debug('STDOUT:\\n %s', res.stdout.decode('utf8'))\n logger.debug('STDERR:\\n %s', res.stderr.decode('utf8'))\n if os.path.isfile(outname):\n logger.debug('Removing file %s', outname)\n os.remove(outname)\n raise SubprocessException('Failed to process ' + source)", "response": "Run the command to resize the video and remove the output file."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef video_size(source, converter='ffmpeg'):\n\n res = subprocess.run([converter, '-i', source], stderr=subprocess.PIPE)\n stderr = res.stderr.decode('utf8')\n pattern = re.compile(r'Stream.*Video.* ([0-9]+)x([0-9]+)')\n match = pattern.search(stderr)\n rot_pattern = re.compile(r'rotate\\s*:\\s*-?(90|270)')\n rot_match = rot_pattern.search(stderr)\n\n if match:\n x, y = int(match.groups()[0]), int(match.groups()[1])\n else:\n x = y = 0\n if rot_match:\n x, y = y, x\n return x, y", "response": "Returns the dimensions of the video."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngenerates a new video from a source file.", "response": "def generate_video(source, outname, settings, options=None):\n \"\"\"Video processor.\n\n :param source: path to a video\n :param outname: path to the generated video\n :param settings: settings dict\n :param options: array of options passed to ffmpeg\n\n \"\"\"\n logger = logging.getLogger(__name__)\n\n # Don't transcode if source is in the required format and\n # has fitting datedimensions, copy instead.\n converter = settings['video_converter']\n w_src, h_src = video_size(source, converter=converter)\n w_dst, h_dst = settings['video_size']\n logger.debug('Video size: %i, %i -> %i, %i', w_src, h_src, w_dst, h_dst)\n\n base, src_ext = splitext(source)\n base, dst_ext = splitext(outname)\n if dst_ext == src_ext and w_src <= w_dst and h_src <= h_dst:\n logger.debug('Video is smaller than the max size, copying it instead')\n shutil.copy(source, outname)\n return\n\n # http://stackoverflow.com/questions/8218363/maintaining-ffmpeg-aspect-ratio\n # + I made a drawing on paper to figure this out\n if h_dst * w_src < h_src * w_dst:\n # biggest fitting dimension is height\n resize_opt = ['-vf', \"scale=trunc(oh*a/2)*2:%i\" % h_dst]\n else:\n # biggest fitting dimension is width\n resize_opt = ['-vf', \"scale=%i:trunc(ow/a/2)*2\" % w_dst]\n\n # do not resize if input dimensions are smaller than output dimensions\n if w_src <= w_dst and h_src <= h_dst:\n resize_opt = []\n\n # Encoding options improved, thanks to\n # http://ffmpeg.org/trac/ffmpeg/wiki/vpxEncodingGuide\n cmd = [converter, '-i', source, '-y'] # -y to overwrite output files\n if options is not None:\n cmd += options\n cmd += resize_opt + [outname]\n\n logger.debug('Processing video: %s', ' '.join(cmd))\n check_subprocess(cmd, source, outname)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngenerates a thumbnail image for the video source based on ffmpeg.", "response": "def generate_thumbnail(source, outname, box, delay, fit=True, options=None,\n converter='ffmpeg'):\n \"\"\"Create a thumbnail image for the video source, based on ffmpeg.\"\"\"\n\n logger = logging.getLogger(__name__)\n tmpfile = outname + \".tmp.jpg\"\n\n # dump an image of the video\n cmd = [converter, '-i', source, '-an', '-r', '1',\n '-ss', delay, '-vframes', '1', '-y', tmpfile]\n logger.debug('Create thumbnail for video: %s', ' '.join(cmd))\n check_subprocess(cmd, source, outname)\n\n # use the generate_thumbnail function from sigal.image\n image.generate_thumbnail(tmpfile, outname, box, fit=fit, options=options)\n # remove the image\n os.unlink(tmpfile)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nprocesses a video resize create thumbnail.", "response": "def process_video(filepath, outpath, settings):\n \"\"\"Process a video: resize, create thumbnail.\"\"\"\n\n logger = logging.getLogger(__name__)\n filename = os.path.split(filepath)[1]\n basename, ext = splitext(filename)\n\n try:\n if settings['use_orig'] and is_valid_html5_video(ext):\n outname = os.path.join(outpath, filename)\n utils.copy(filepath, outname, symlink=settings['orig_link'])\n else:\n valid_formats = ['mp4', 'webm']\n video_format = settings['video_format']\n\n if video_format not in valid_formats:\n logger.error('Invalid video_format. Please choose one of: %s',\n valid_formats)\n raise ValueError\n\n outname = os.path.join(outpath, basename + '.' + video_format)\n generate_video(filepath, outname, settings,\n options=settings.get(video_format + '_options'))\n except Exception:\n if logger.getEffectiveLevel() == logging.DEBUG:\n raise\n else:\n return Status.FAILURE\n\n if settings['make_thumbs']:\n thumb_name = os.path.join(outpath, get_thumb(settings, filename))\n try:\n generate_thumbnail(\n outname, thumb_name, settings['thumb_size'],\n settings['thumb_video_delay'], fit=settings['thumb_fit'],\n options=settings['jpg_options'],\n converter=settings['video_converter'])\n except Exception:\n if logger.getEffectiveLevel() == logging.DEBUG:\n raise\n else:\n return Status.FAILURE\n\n return Status.SUCCESS"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nlogging config Set the level and create a more detailed formatter for debug mode.", "response": "def init_logging(name, level=logging.INFO):\n \"\"\"Logging config\n\n Set the level and create a more detailed formatter for debug mode.\n\n \"\"\"\n logger = logging.getLogger(name)\n logger.setLevel(level)\n\n try:\n if os.isatty(sys.stdout.fileno()) and \\\n not sys.platform.startswith('win'):\n formatter = ColoredFormatter()\n elif level == logging.DEBUG:\n formatter = Formatter('%(levelname)s - %(message)s')\n else:\n formatter = Formatter('%(message)s')\n except Exception:\n # This fails when running tests with click (test_build)\n formatter = Formatter('%(message)s')\n\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n logger.addHandler(handler)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngenerates the context dict for the given path.", "response": "def generate_context(self, album):\n \"\"\"Generate the context dict for the given path.\"\"\"\n\n from . import __url__ as sigal_link\n self.logger.info(\"Output album : %r\", album)\n return {\n 'album': album,\n 'index_title': self.index_title,\n 'settings': self.settings,\n 'sigal_link': sigal_link,\n 'theme': {'name': os.path.basename(self.theme),\n 'url': url_from_path(os.path.relpath(self.theme_path,\n album.dst_path))},\n }"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef write(self, album):\n\n page = self.template.render(**self.generate_context(album))\n output_file = os.path.join(album.dst_path, album.output_file)\n\n with open(output_file, 'w', encoding='utf-8') as f:\n f.write(page)", "response": "Generate the HTML page and save it."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_thumb(settings, filename):\n\n path, filen = os.path.split(filename)\n name, ext = os.path.splitext(filen)\n\n if ext.lower() in settings['video_extensions']:\n ext = '.jpg'\n return join(path, settings['thumb_dir'], settings['thumb_prefix'] +\n name + settings['thumb_suffix'] + ext)", "response": "Return the path to the thumb."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nread settings from a config file in the source_dir root.", "response": "def read_settings(filename=None):\n \"\"\"Read settings from a config file in the source_dir root.\"\"\"\n\n logger = logging.getLogger(__name__)\n logger.info(\"Reading settings ...\")\n settings = _DEFAULT_CONFIG.copy()\n\n if filename:\n logger.debug(\"Settings file: %s\", filename)\n settings_path = os.path.dirname(filename)\n tempdict = {}\n\n with open(filename) as f:\n code = compile(f.read(), filename, 'exec')\n exec(code, tempdict)\n\n settings.update((k, v) for k, v in tempdict.items()\n if k not in ['__builtins__'])\n\n # Make the paths relative to the settings file\n paths = ['source', 'destination', 'watermark']\n\n if os.path.isdir(join(settings_path, settings['theme'])) and \\\n os.path.isdir(join(settings_path, settings['theme'],\n 'templates')):\n paths.append('theme')\n\n for p in paths:\n path = settings[p]\n if path and not isabs(path):\n settings[p] = abspath(normpath(join(settings_path, path)))\n logger.debug(\"Rewrite %s : %s -> %s\", p, path, settings[p])\n\n for key in ('img_size', 'thumb_size', 'video_size'):\n w, h = settings[key]\n if h > w:\n settings[key] = (h, w)\n logger.warning(\"The %s setting should be specified with the \"\n \"largest value first.\", key)\n\n if not settings['img_processor']:\n logger.info('No Processor, images will not be resized')\n\n logger.debug('Settings:\\n%s', pformat(settings, width=120))\n return settings"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef generate_media_pages(gallery):\n '''Generates and writes the media pages for all media in the gallery'''\n\n writer = PageWriter(gallery.settings, index_title=gallery.title)\n\n for album in gallery.albums.values():\n medias = album.medias\n next_medias = medias[1:] + [None]\n previous_medias = [None] + medias[:-1]\n\n # The media group allows us to easily get next and previous links\n media_groups = zip(medias, next_medias, previous_medias)\n\n for media_group in media_groups:\n writer.write(album, media_group)", "response": "Generates and writes the media pages for all media in the gallery"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef write(self, album, media_group):\n ''' Generate the media page and save it '''\n\n from sigal import __url__ as sigal_link\n file_path = os.path.join(album.dst_path, media_group[0].filename)\n\n page = self.template.render({\n 'album': album,\n 'media': media_group[0],\n 'previous_media': media_group[-1],\n 'next_media': media_group[1],\n 'index_title': self.index_title,\n 'settings': self.settings,\n 'sigal_link': sigal_link,\n 'theme': {'name': os.path.basename(self.theme),\n 'url': url_from_path(os.path.relpath(self.theme_path,\n album.dst_path))},\n })\n\n output_file = \"%s.html\" % file_path\n\n with open(output_file, 'w', encoding='utf-8') as f:\n f.write(page)", "response": "Generate the media page and save it"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef check_install(config_data):\n errors = []\n\n # PIL tests\n try:\n from PIL import Image\n\n try:\n im = Image.open(os.path.join(os.path.dirname(__file__), '../share/test_image.png'))\n im.load()\n except IOError: # pragma: no cover\n errors.append(\n 'Pillow is not compiled with PNG support, see \"Libraries installation issues\" '\n 'documentation section: https://djangocms-installer.readthedocs.io/en/latest/'\n 'libraries.html.'\n )\n try:\n im = Image.open(os.path.join(os.path.dirname(__file__), '../share/test_image.jpg'))\n im.load()\n except IOError: # pragma: no cover\n errors.append(\n 'Pillow is not compiled with JPEG support, see \"Libraries installation issues\" '\n 'documentation section: https://djangocms-installer.readthedocs.io/en/latest/'\n 'libraries.html'\n )\n except ImportError: # pragma: no cover\n errors.append(\n 'Pillow is not installed check for installation errors and see \"Libraries installation'\n ' issues\" documentation section: https://djangocms-installer.readthedocs.io/en/latest/'\n 'libraries.html'\n )\n\n # PostgreSQL test\n if config_data.db_driver == 'psycopg2' and not config_data.no_db_driver: # pragma: no cover\n try:\n import psycopg2 # NOQA\n except ImportError:\n errors.append(\n 'PostgreSQL driver is not installed, but you configured a PostgreSQL database, '\n 'please check your installation and see \"Libraries installation issues\" '\n 'documentation section: https://djangocms-installer.readthedocs.io/en/latest/'\n 'libraries.html'\n )\n\n # MySQL test\n if config_data.db_driver == 'mysqlclient' and not config_data.no_db_driver: # pragma: no cover # NOQA\n try:\n import MySQLdb # NOQA\n except ImportError:\n errors.append(\n 'MySQL driver is not installed, but you configured a MySQL database, please check '\n 'your installation and see \"Libraries installation issues\" documentation section: '\n 'https://djangocms-installer.readthedocs.io/en/latest/libraries.html'\n )\n if errors: # pragma: no cover\n raise EnvironmentError('\\n'.join(errors))", "response": "Check that the Pillow and Pillow images are installed and that they are not missing."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef cleanup_directory(config_data):\n if os.path.exists(config_data.project_directory):\n choice = False\n if config_data.noinput is False and not config_data.verbose:\n choice = query_yes_no(\n 'The installation failed.\\n'\n 'Do you want to clean up by removing {0}?\\n'\n '\\tWarning: this will delete all files in:\\n'\n '\\t\\t{0}\\n'\n 'Do you want to cleanup?'.format(\n os.path.abspath(config_data.project_directory)\n ),\n 'no'\n )\n else:\n sys.stdout.write('The installation has failed.\\n')\n if config_data.skip_project_dir_check is False and (choice or\n (config_data.noinput and\n config_data.delete_project_dir)):\n sys.stdout.write('Removing everything under {0}\\n'.format(\n os.path.abspath(config_data.project_directory)\n ))\n shutil.rmtree(config_data.project_directory, True)", "response": "Removes the project directory if it exists and if it does not exist."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef validate_project(project_name):\n if '-' in project_name:\n return None\n if keyword.iskeyword(project_name):\n return None\n if project_name in dir(__builtins__):\n return None\n try:\n __import__(project_name)\n return None\n except ImportError:\n return project_name", "response": "Check the project name against keywords builtins and existing\n modules to avoid name clashing"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nparsing command line arguments and return a list of arguments.", "response": "def parse(args):\n \"\"\"\n Define the available arguments\n \"\"\"\n from tzlocal import get_localzone\n\n try:\n timezone = get_localzone()\n if isinstance(timezone, pytz.BaseTzInfo):\n timezone = timezone.zone\n except Exception: # pragma: no cover\n timezone = 'UTC'\n if timezone == 'local':\n timezone = 'UTC'\n parser = argparse.ArgumentParser(description=\"\"\"Bootstrap a django CMS project.\nMajor usage modes:\n\n- wizard: djangocms -w -p /path/whatever project_name: ask for all the options through a\n CLI wizard.\n\n- batch: djangocms project_name: runs with the default values plus any\n additional option provided (see below) with no question asked.\n\n- config file: djangocms_installer --config-file /path/to/config.ini project_name: reads values\n from an ini-style config file.\n\nCheck https://djangocms-installer.readthedocs.io/en/latest/usage.html for detailed usage\ninformation.\n\"\"\", formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('--config-file', dest='config_file', action='store',\n default=None,\n help='Configuration file for djangocms_installer')\n parser.add_argument('--config-dump', dest='config_dump', action='store',\n default=None,\n help='Dump configuration file with current args')\n parser.add_argument('--db', '-d', dest='db', action=DbAction,\n default='sqlite://localhost/project.db',\n help='Database configuration (in URL format). '\n 'Example: sqlite://localhost/project.db')\n parser.add_argument('--i18n', '-i', dest='i18n', action='store',\n choices=('yes', 'no'),\n default='yes', help='Activate Django I18N / L10N setting; this is '\n 'automatically activated if more than '\n 'language is provided')\n parser.add_argument('--use-tz', '-z', dest='use_timezone', action='store',\n choices=('yes', 'no'),\n default='yes', help='Activate Django timezone support')\n parser.add_argument('--timezone', '-t', dest='timezone',\n required=False, default=timezone,\n action='store', help='Optional default time zone. Example: Europe/Rome')\n parser.add_argument('--reversion', '-e', dest='reversion', action='store',\n choices=('yes', 'no'),\n default='yes', help='Install and configure reversion support '\n '(only for django CMS 3.2 and 3.3)')\n parser.add_argument('--permissions', dest='permissions', action='store',\n choices=('yes', 'no'),\n default='no', help='Activate CMS permission management')\n parser.add_argument('--pip-options', help='pass custom pip options', default='')\n parser.add_argument('--languages', '-l', dest='languages', action='append',\n help='Languages to enable. Option can be provided multiple times, or as a '\n 'comma separated list. Only language codes supported by Django can '\n 'be used here. Example: en, fr-FR, it-IT')\n parser.add_argument('--django-version', dest='django_version', action='store',\n choices=data.DJANGO_SUPPORTED,\n default=data.DJANGO_DEFAULT, help='Django version')\n parser.add_argument('--cms-version', '-v', dest='cms_version', action='store',\n choices=data.DJANGOCMS_SUPPORTED,\n default=data.DJANGOCMS_DEFAULT, help='django CMS version')\n parser.add_argument('--parent-dir', '-p', dest='project_directory',\n default='',\n action='store', help='Optional project parent directory')\n parser.add_argument('--bootstrap', dest='bootstrap', action='store',\n choices=('yes', 'no'),\n default='no', help='Use Twitter Bootstrap Theme')\n parser.add_argument('--templates', dest='templates', action='store',\n default='no', help='Use custom template set')\n parser.add_argument('--starting-page', dest='starting_page', action='store',\n choices=('yes', 'no'),\n default='no', help='Load a starting page with examples after installation '\n '(english language only). Choose \"no\" if you use a '\n 'custom template set.')\n parser.add_argument(dest='project_name', action='store',\n help='Name of the project to be created')\n\n # Command that lists the supported plugins in verbose description\n parser.add_argument('--list-plugins', '-P', dest='plugins', action='store_true',\n help='List plugins that\\'s going to be installed and configured')\n\n # Command that lists the supported plugins in verbose description\n parser.add_argument('--dump-requirements', '-R', dest='dump_reqs', action='store_true',\n help='It dumps the requirements that would be installed according to '\n 'parameters given. Together with --requirements argument is useful '\n 'for customizing the virtualenv')\n\n # Advanced options. These have a predefined default and are not asked\n # by config wizard.\n parser.add_argument('--no-input', '-q', dest='noinput', action='store_true',\n default=True, help='Don\\'t run the configuration wizard, just use the '\n 'provided values')\n parser.add_argument('--wizard', '-w', dest='wizard', action='store_true',\n default=False, help='Run the configuration wizard')\n parser.add_argument('--verbose', dest='verbose', action='store_true',\n default=False,\n help='Be more verbose and don\\'t swallow subcommands output')\n parser.add_argument('--filer', '-f', dest='filer', action='store_true',\n default=True, help='Install and configure django-filer plugins '\n '- Always enabled')\n parser.add_argument('--requirements', '-r', dest='requirements_file', action='store',\n default=None, help='Externally defined requirements file')\n parser.add_argument('--no-deps', '-n', dest='no_deps', action='store_true',\n default=False, help='Don\\'t install package dependencies')\n parser.add_argument('--no-plugins', dest='no_plugins', action='store_true',\n default=False, help='Don\\'t install plugins')\n parser.add_argument('--no-db-driver', dest='no_db_driver', action='store_true',\n default=False, help='Don\\'t install database package')\n parser.add_argument('--no-sync', '-m', dest='no_sync', action='store_true',\n default=False, help='Don\\'t run syncdb / migrate after bootstrapping')\n parser.add_argument('--no-user', '-u', dest='no_user', action='store_true',\n default=False, help='Don\\'t create the admin user')\n parser.add_argument('--template', dest='template', action='store',\n default=None, help='The path or URL to load the django project '\n 'template from.')\n parser.add_argument('--extra-settings', dest='extra_settings', action='store',\n default=None, help='The path to an file that contains extra settings.')\n parser.add_argument('--skip-empty-check', '-s', dest='skip_project_dir_check',\n action='store_true',\n default=False, help='Skip the check if project dir is empty.')\n parser.add_argument('--delete-project-dir', '-c', dest='delete_project_dir',\n action='store_true',\n default=False, help='Delete project directory on creation failure.')\n parser.add_argument('--utc', dest='utc',\n action='store_true',\n default=False, help='Use UTC timezone.')\n\n if '--utc' in args:\n for action in parser._positionals._actions:\n if action.dest == 'timezone':\n action.default = 'UTC'\n\n # If config_args then pretend that config args came from the stdin and run parser again.\n config_args = ini.parse_config_file(parser, args)\n args = parser.parse_args(config_args + args)\n if not args.wizard:\n args.noinput = True\n else:\n args.noinput = False\n\n if not args.project_directory:\n args.project_directory = args.project_name\n args.project_directory = os.path.abspath(args.project_directory)\n\n # First of all, check if the project name is valid\n if not validate_project(args.project_name):\n sys.stderr.write(\n 'Project name \"{0}\" is not a valid app name, or it\\'s already defined. '\n 'Please use only numbers, letters and underscores.\\n'.format(args.project_name)\n )\n sys.exit(3)\n\n # Checking the given path\n setattr(args, 'project_path', os.path.join(args.project_directory, args.project_name).strip())\n if not args.skip_project_dir_check:\n if (os.path.exists(args.project_directory) and\n [path for path in os.listdir(args.project_directory) if not path.startswith('.')]):\n sys.stderr.write(\n 'Path \"{0}\" already exists and is not empty, please choose a different one\\n'\n 'If you want to use this path anyway use the -s flag to skip this check.\\n'\n ''.format(args.project_directory)\n )\n sys.exit(4)\n\n if os.path.exists(args.project_path):\n sys.stderr.write(\n 'Path \"{0}\" already exists, please choose a different one\\n'.format(args.project_path)\n )\n sys.exit(4)\n\n if args.config_dump and os.path.isfile(args.config_dump):\n sys.stdout.write(\n 'Cannot dump because given configuration file \"{0}\" exists.\\n'.format(args.config_dump)\n )\n sys.exit(8)\n\n args = _manage_args(parser, args)\n\n # what do we want here?!\n # * if languages are given as multiple arguments, let's use it as is\n # * if no languages are given, use a default and stop handling it further\n # * if languages are given as a comma-separated list, split it and use the\n # resulting list.\n\n if not args.languages:\n try:\n args.languages = [locale.getdefaultlocale()[0].split('_')[0]]\n except Exception: # pragma: no cover\n args.languages = ['en']\n elif isinstance(args.languages, six.string_types):\n args.languages = args.languages.split(',')\n elif len(args.languages) == 1 and isinstance(args.languages[0], six.string_types):\n args.languages = args.languages[0].split(',')\n\n args.languages = [lang.strip().lower() for lang in args.languages]\n if len(args.languages) > 1:\n args.i18n = 'yes'\n args.aldryn = False\n args.filer = True\n\n # Convert version to numeric format for easier checking\n try:\n django_version, cms_version = supported_versions(args.django_version, args.cms_version)\n cms_package = data.PACKAGE_MATRIX.get(\n cms_version, data.PACKAGE_MATRIX[data.DJANGOCMS_LTS]\n )\n except RuntimeError as e: # pragma: no cover\n sys.stderr.write(compat.unicode(e))\n sys.exit(6)\n if django_version is None: # pragma: no cover\n sys.stderr.write(\n 'Please provide a Django supported version: {0}. Only Major.Minor '\n 'version selector is accepted\\n'.format(', '.join(data.DJANGO_SUPPORTED))\n )\n sys.exit(6)\n if cms_version is None: # pragma: no cover\n sys.stderr.write(\n 'Please provide a django CMS supported version: {0}. Only Major.Minor '\n 'version selector is accepted\\n'.format(', '.join(data.DJANGOCMS_SUPPORTED))\n )\n sys.exit(6)\n\n default_settings = '{}.settings'.format(args.project_name)\n env_settings = os.environ.get('DJANGO_SETTINGS_MODULE', default_settings)\n if env_settings != default_settings:\n sys.stderr.write(\n '`DJANGO_SETTINGS_MODULE` is currently set to \\'{0}\\' which is not compatible with '\n 'djangocms installer.\\nPlease unset `DJANGO_SETTINGS_MODULE` and re-run the installer '\n '\\n'.format(env_settings)\n )\n sys.exit(10)\n\n if not getattr(args, 'requirements_file'):\n requirements = []\n\n # django CMS version check\n if args.cms_version == 'develop':\n requirements.append(cms_package)\n warnings.warn(data.VERSION_WARNING.format('develop', 'django CMS'))\n elif args.cms_version == 'rc': # pragma: no cover\n requirements.append(cms_package)\n elif args.cms_version == 'beta': # pragma: no cover\n requirements.append(cms_package)\n warnings.warn(data.VERSION_WARNING.format('beta', 'django CMS'))\n else:\n requirements.append(cms_package)\n\n if args.cms_version in ('rc', 'develop'):\n requirements.extend(data.REQUIREMENTS['cms-master'])\n elif LooseVersion(cms_version) >= LooseVersion('3.6'):\n requirements.extend(data.REQUIREMENTS['cms-3.6'])\n elif LooseVersion(cms_version) >= LooseVersion('3.5'):\n requirements.extend(data.REQUIREMENTS['cms-3.5'])\n elif LooseVersion(cms_version) >= LooseVersion('3.4'):\n requirements.extend(data.REQUIREMENTS['cms-3.4'])\n\n if not args.no_db_driver:\n requirements.append(args.db_driver)\n if not args.no_plugins:\n if args.cms_version in ('rc', 'develop'):\n requirements.extend(data.REQUIREMENTS['plugins-master'])\n elif LooseVersion(cms_version) >= LooseVersion('3.6'):\n requirements.extend(data.REQUIREMENTS['plugins-3.6'])\n elif LooseVersion(cms_version) >= LooseVersion('3.5'):\n requirements.extend(data.REQUIREMENTS['plugins-3.5'])\n elif LooseVersion(cms_version) >= LooseVersion('3.4'):\n requirements.extend(data.REQUIREMENTS['plugins-3.4'])\n requirements.extend(data.REQUIREMENTS['filer'])\n\n if args.aldryn: # pragma: no cover\n requirements.extend(data.REQUIREMENTS['aldryn'])\n\n # Django version check\n if args.django_version == 'develop': # pragma: no cover\n requirements.append(data.DJANGO_DEVELOP)\n warnings.warn(data.VERSION_WARNING.format('develop', 'Django'))\n elif args.django_version == 'beta': # pragma: no cover\n requirements.append(data.DJANGO_BETA)\n warnings.warn(data.VERSION_WARNING.format('beta', 'Django'))\n else:\n requirements.append('Django<{0}'.format(less_than_version(django_version)))\n\n if django_version == '1.8':\n requirements.extend(data.REQUIREMENTS['django-1.8'])\n elif django_version == '1.9':\n requirements.extend(data.REQUIREMENTS['django-1.9'])\n elif django_version == '1.10':\n requirements.extend(data.REQUIREMENTS['django-1.10'])\n elif django_version == '1.11':\n requirements.extend(data.REQUIREMENTS['django-1.11'])\n elif django_version == '2.0':\n requirements.extend(data.REQUIREMENTS['django-2.0'])\n elif django_version == '2.1':\n requirements.extend(data.REQUIREMENTS['django-2.1'])\n\n requirements.extend(data.REQUIREMENTS['default'])\n\n setattr(args, 'requirements', '\\n'.join(requirements).strip())\n\n # Convenient shortcuts\n setattr(args, 'cms_version', cms_version)\n setattr(args, 'django_version', django_version)\n setattr(args, 'settings_path',\n os.path.join(args.project_directory, args.project_name, 'settings.py').strip())\n setattr(args, 'urlconf_path',\n os.path.join(args.project_directory, args.project_name, 'urls.py').strip())\n\n if args.config_dump:\n ini.dump_config_file(args.config_dump, args, parser)\n\n return args"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nmanage the arguments for the configuration file.", "response": "def _manage_args(parser, args):\n \"\"\"\n Checks and validate provided input\n \"\"\"\n for item in data.CONFIGURABLE_OPTIONS:\n action = parser._option_string_actions[item]\n choices = default = ''\n input_value = getattr(args, action.dest)\n new_val = None\n # cannot count this until we find a way to test input\n if not args.noinput: # pragma: no cover\n if action.choices:\n choices = ' (choices: {0})'.format(', '.join(action.choices))\n if input_value:\n if type(input_value) == list:\n default = ' [default {0}]'.format(', '.join(input_value))\n else:\n default = ' [default {0}]'.format(input_value)\n\n while not new_val:\n prompt = '{0}{1}{2}: '.format(action.help, choices, default)\n if action.choices in ('yes', 'no'):\n new_val = utils.query_yes_no(prompt)\n else:\n new_val = compat.input(prompt)\n new_val = compat.clean(new_val)\n if not new_val and input_value:\n new_val = input_value\n if new_val and action.dest == 'templates':\n if new_val != 'no' and not os.path.isdir(new_val):\n sys.stdout.write('Given directory does not exists, retry\\n')\n new_val = False\n if new_val and action.dest == 'db':\n action(parser, args, new_val, action.option_strings)\n new_val = getattr(args, action.dest)\n else:\n if not input_value and action.required:\n raise ValueError(\n 'Option {0} is required when in no-input mode'.format(action.dest)\n )\n new_val = input_value\n if action.dest == 'db':\n action(parser, args, new_val, action.option_strings)\n new_val = getattr(args, action.dest)\n if action.dest == 'templates' and (new_val == 'no' or not os.path.isdir(new_val)):\n new_val = False\n if action.dest in ('bootstrap', 'starting_page'):\n new_val = (new_val == 'yes')\n setattr(args, action.dest, new_val)\n return args"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nask a yes or no question via raw_input and return their answer.", "response": "def query_yes_no(question, default=None): # pragma: no cover\n \"\"\"\n Ask a yes/no question via `raw_input()` and return their answer.\n\n :param question: A string that is presented to the user.\n :param default: The presumed answer if the user just hits .\n It must be \"yes\" (the default), \"no\" or None (meaning\n an answer is required of the user).\n\n The \"answer\" return value is one of \"yes\" or \"no\".\n\n Code borrowed from cookiecutter\n https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py\n \"\"\"\n valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False}\n if default is None:\n prompt = ' [y/n] '\n elif default == 'yes':\n prompt = ' [Y/n] '\n elif default == 'no':\n prompt = ' [y/N] '\n else:\n raise ValueError('invalid default answer: \"{0}\"'.format(default))\n\n while True:\n sys.stdout.write(question + prompt)\n choice = compat.input().lower()\n\n if default is not None and choice == '':\n return valid[default]\n elif choice in valid:\n return valid[choice]\n else:\n sys.stdout.write('Please answer with \"yes\" or \"no\" (or \"y\" or \"n\").\\n')"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nconverts numeric and literal version information to numeric format", "response": "def supported_versions(django, cms):\n \"\"\"\n Convert numeric and literal version information to numeric format\n \"\"\"\n cms_version = None\n django_version = None\n\n try:\n cms_version = Decimal(cms)\n except (ValueError, InvalidOperation):\n try:\n cms_version = CMS_VERSION_MATRIX[str(cms)]\n except KeyError:\n pass\n\n try:\n django_version = Decimal(django)\n except (ValueError, InvalidOperation):\n try:\n django_version = DJANGO_VERSION_MATRIX[str(django)]\n except KeyError: # pragma: no cover\n pass\n\n try:\n if (\n cms_version and django_version and\n not (LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][0]) <=\n LooseVersion(compat.unicode(django_version)) <=\n LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][1]))\n ):\n raise RuntimeError(\n 'Django and django CMS versions doesn\\'t match: '\n 'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version)\n )\n except KeyError:\n raise RuntimeError(\n 'Django and django CMS versions doesn\\'t match: '\n 'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version)\n )\n return (\n compat.unicode(django_version) if django_version else django_version,\n compat.unicode(cms_version) if cms_version else cms_version\n )"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef less_than_version(value):\n items = list(map(int, str(value).split('.')))\n if len(items) == 1:\n items.append(0)\n items[1] += 1\n if value == '1.11':\n return '2.0'\n else:\n return '.'.join(map(str, items))", "response": "Converts the current version to the next one for inserting into requirements\n in the < version format"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef format_val(val):\n val = text_type(val)\n if val.isdigit():\n return int(val)\n else:\n return '\\'{0}\\''.format(val)", "response": "Returns val as integer or as escaped string according to its value\n "}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef parse_config_file(parser, stdin_args):\n config_args = []\n\n # Temporary switch required args and save them to restore.\n required_args = []\n for action in parser._actions:\n if action.required:\n required_args.append(action)\n action.required = False\n\n parsed_args = parser.parse_args(stdin_args)\n\n # Restore required args.\n for action in required_args:\n action.required = True\n\n if not parsed_args.config_file:\n return config_args\n\n config = ConfigParser()\n if not config.read(parsed_args.config_file):\n sys.stderr.write('Config file \"{0}\" doesn\\'t exists\\n'.format(parsed_args.config_file))\n sys.exit(7) # It isn't used anywhere.\n\n config_args = _convert_config_to_stdin(config, parser)\n return config_args", "response": "Parse config file.\n\n Returns a list of additional args."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ndumping args to config file.", "response": "def dump_config_file(filename, args, parser=None):\n \"\"\"Dump args to config file.\"\"\"\n config = ConfigParser()\n config.add_section(SECTION)\n if parser is None:\n for attr in args:\n config.set(SECTION, attr, args.attr)\n else:\n keys_empty_values_not_pass = (\n '--extra-settings', '--languages', '--requirements', '--template', '--timezone')\n\n # positionals._option_string_actions\n for action in parser._actions:\n if action.dest in ('help', 'config_file', 'config_dump', 'project_name'):\n continue\n\n keyp = action.option_strings[0]\n option_name = keyp.lstrip('-')\n option_value = getattr(args, action.dest)\n if any([i for i in keys_empty_values_not_pass if i in action.option_strings]):\n if action.dest == 'languages':\n if len(option_value) == 1 and option_value[0] == 'en':\n config.set(SECTION, option_name, '')\n else:\n config.set(SECTION, option_name, ','.join(option_value))\n else:\n config.set(SECTION, option_name, option_value if option_value else '')\n elif action.choices == ('yes', 'no'):\n config.set(SECTION, option_name, 'yes' if option_value else 'no')\n elif action.dest == 'templates':\n config.set(SECTION, option_name, option_value if option_value else 'no')\n elif action.dest == 'cms_version':\n version = ('stable' if option_value == CMS_VERSION_MATRIX['stable']\n else option_value)\n config.set(SECTION, option_name, version)\n elif action.dest == 'django_version':\n version = ('stable' if option_value == DJANGO_VERSION_MATRIX['stable']\n else option_value)\n config.set(SECTION, option_name, version)\n elif action.const:\n config.set(SECTION, option_name, 'true' if option_value else 'false')\n else:\n config.set(SECTION, option_name, str(option_value))\n with open(filename, 'w') as fp:\n config.write(fp)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _convert_config_to_stdin(config, parser):\n keys_empty_values_not_pass = (\n '--extra-settings', '--languages', '--requirements', '--template', '--timezone')\n args = []\n for key, val in config.items(SECTION):\n keyp = '--{0}'.format(key)\n action = parser._option_string_actions[keyp]\n\n if action.const:\n try:\n if config.getboolean(SECTION, key):\n args.append(keyp)\n except ValueError:\n args.extend([keyp, val]) # Pass it as is to get the error from ArgumentParser.\n elif any([i for i in keys_empty_values_not_pass if i in action.option_strings]):\n # Some keys with empty values shouldn't be passed into args to use their defaults\n # from ArgumentParser.\n if val != '':\n args.extend([keyp, val])\n else:\n args.extend([keyp, val])\n\n return args", "response": "Convert config options to stdin args.\ninel Especially boolean values for more information\ninel"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef create_project(config_data):\n env = deepcopy(dict(os.environ))\n env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))\n env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path)))\n kwargs = {}\n args = []\n if config_data.template:\n kwargs['template'] = config_data.template\n args.append(config_data.project_name)\n if config_data.project_directory:\n args.append(config_data.project_directory)\n if not os.path.exists(config_data.project_directory):\n os.makedirs(config_data.project_directory)\n base_cmd = 'django-admin.py'\n start_cmds = [os.path.join(os.path.dirname(sys.executable), base_cmd)]\n start_cmd_pnodes = ['Scripts']\n start_cmds.extend([\n os.path.join(os.path.dirname(sys.executable), pnode, base_cmd)\n for pnode in start_cmd_pnodes\n ])\n start_cmd = [base_cmd]\n for p in start_cmds:\n if os.path.exists(p):\n start_cmd = [sys.executable, p]\n break\n cmd_args = start_cmd + ['startproject'] + args\n if config_data.verbose:\n sys.stdout.write('Project creation command: {0}\\n'.format(' '.join(cmd_args)))\n try:\n output = subprocess.check_output(cmd_args, stderr=subprocess.STDOUT)\n sys.stdout.write(output.decode('utf-8'))\n except subprocess.CalledProcessError as e: # pragma: no cover\n if config_data.verbose:\n sys.stdout.write(e.output.decode('utf-8'))\n raise", "response": "Create a new project structure"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ndetects migrations layout for plugins settings and applications", "response": "def _detect_migration_layout(vars, apps):\n \"\"\"\n Detect migrations layout for plugins\n :param vars: installer settings\n :param apps: installed applications\n \"\"\"\n DJANGO_MODULES = {}\n\n for module in vars.MIGRATIONS_CHECK_MODULES:\n if module in apps:\n try:\n mod = __import__('{0}.migrations_django'.format(module)) # NOQA\n DJANGO_MODULES[module] = '{0}.migrations_django'.format(module)\n except Exception:\n pass\n return DJANGO_MODULES"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _install_aldryn(config_data): # pragma: no cover\n import requests\n media_project = os.path.join(config_data.project_directory, 'dist', 'media')\n static_main = False\n static_project = os.path.join(config_data.project_directory, 'dist', 'static')\n template_target = os.path.join(config_data.project_directory, 'templates')\n tmpdir = tempfile.mkdtemp()\n aldrynzip = requests.get(data.ALDRYN_BOILERPLATE)\n zip_open = zipfile.ZipFile(BytesIO(aldrynzip.content))\n zip_open.extractall(path=tmpdir)\n for component in os.listdir(os.path.join(tmpdir, 'aldryn-boilerplate-standard-master')):\n src = os.path.join(tmpdir, 'aldryn-boilerplate-standard-master', component)\n dst = os.path.join(config_data.project_directory, component)\n if os.path.isfile(src):\n shutil.copy(src, dst)\n else:\n shutil.copytree(src, dst)\n shutil.rmtree(tmpdir)\n return media_project, static_main, static_project, template_target", "response": "Installs aldryn boilerplate from aldryn - standard - master."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ncopying all files from the urlconf file to the project directory.", "response": "def copy_files(config_data):\n \"\"\"\n It's a little rude actually: it just overwrites the django-generated urls.py\n with a custom version and put other files in the project directory.\n\n :param config_data: configuration data\n \"\"\"\n if config_data.i18n == 'yes':\n urlconf_path = os.path.join(os.path.dirname(__file__), '../config/urls_i18n.py')\n else:\n urlconf_path = os.path.join(os.path.dirname(__file__), '../config/urls_noi18n.py')\n share_path = os.path.join(os.path.dirname(__file__), '../share')\n template_path = os.path.join(share_path, 'templates')\n if config_data.aldryn: # pragma: no cover\n media_project, static_main, static_project, template_target = _install_aldryn(config_data)\n else:\n media_project = os.path.join(config_data.project_directory, 'media')\n static_main = os.path.join(config_data.project_path, 'static')\n static_project = os.path.join(config_data.project_directory, 'static')\n template_target = os.path.join(config_data.project_path, 'templates')\n if config_data.templates and os.path.isdir(config_data.templates):\n template_path = config_data.templates\n elif config_data.bootstrap:\n template_path = os.path.join(template_path, 'bootstrap')\n else:\n template_path = os.path.join(template_path, 'basic')\n\n shutil.copy(urlconf_path, config_data.urlconf_path)\n if media_project:\n os.makedirs(media_project)\n if static_main:\n os.makedirs(static_main)\n if not os.path.exists(static_project):\n os.makedirs(static_project)\n if not os.path.exists(template_target):\n os.makedirs(template_target)\n for filename in glob.glob(os.path.join(template_path, '*.html')):\n if os.path.isfile(filename):\n shutil.copy(filename, template_target)\n\n if config_data.noinput and not config_data.no_user:\n script_path = os.path.join(share_path, 'create_user.py')\n if os.path.isfile(script_path):\n shutil.copy(script_path, os.path.join(config_data.project_path, '..'))\n\n if config_data.starting_page:\n for filename in glob.glob(os.path.join(share_path, 'starting_page.*')):\n if os.path.isfile(filename):\n shutil.copy(filename, os.path.join(config_data.project_path, '..'))"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\npatches the settings file created by Django injecting the django CMS configuration", "response": "def patch_settings(config_data):\n \"\"\"\n Modify the settings file created by Django injecting the django CMS\n configuration\n\n :param config_data: configuration data\n \"\"\"\n import django\n current_django_version = LooseVersion(django.__version__)\n declared_django_version = LooseVersion(config_data.django_version)\n\n if not os.path.exists(config_data.settings_path):\n sys.stderr.write(\n 'Error while creating target project, '\n 'please check the given configuration: {0}\\n'.format(config_data.settings_path)\n )\n return sys.exit(5)\n\n if current_django_version.version[:2] != declared_django_version.version[:2]:\n sys.stderr.write(\n 'Currently installed Django version {} differs from the declared {}. '\n 'Please check the given `--django-version` installer argument, your virtualenv '\n 'configuration and any package forcing a different Django version'\n '\\n'.format(\n current_django_version, declared_django_version\n )\n )\n return sys.exit(9)\n\n overridden_settings = (\n 'MIDDLEWARE_CLASSES', 'MIDDLEWARE', 'INSTALLED_APPS', 'TEMPLATE_LOADERS',\n 'TEMPLATE_CONTEXT_PROCESSORS', 'TEMPLATE_DIRS', 'LANGUAGES'\n )\n extra_settings = ''\n\n with open(config_data.settings_path, 'r') as fd_original:\n original = fd_original.read()\n\n # extra settings reading\n if config_data.extra_settings and os.path.exists(config_data.extra_settings):\n with open(config_data.extra_settings, 'r') as fd_extra:\n extra_settings = fd_extra.read()\n\n original = original.replace('# -*- coding: utf-8 -*-\\n', '')\n\n if config_data.aldryn: # pragma: no cover\n DATA_DIR = (\n 'DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), \\'dist\\')\\n'\n )\n STATICFILES_DIR = 'os.path.join(BASE_DIR, \\'static\\'),'\n else:\n DATA_DIR = 'DATA_DIR = os.path.dirname(os.path.dirname(__file__))\\n'\n STATICFILES_DIR = 'os.path.join(BASE_DIR, \\'{0}\\', \\'static\\'),'.format(\n config_data.project_name\n )\n\n original = data.DEFAULT_PROJECT_HEADER + DATA_DIR + original\n original += 'MEDIA_URL = \\'/media/\\'\\n'\n original += 'MEDIA_ROOT = os.path.join(DATA_DIR, \\'media\\')\\n'\n original += 'STATIC_ROOT = os.path.join(DATA_DIR, \\'static\\')\\n'\n original += \"\"\"\nSTATICFILES_DIRS = (\n {0}\n)\n\"\"\".format(STATICFILES_DIR)\n original = original.replace('# -*- coding: utf-8 -*-\\n', '')\n\n # I18N\n if config_data.i18n == 'no':\n original = original.replace('I18N = True', 'I18N = False')\n original = original.replace('L10N = True', 'L10N = False')\n\n # TZ\n if config_data.use_timezone == 'no':\n original = original.replace('USE_TZ = True', 'USE_TZ = False')\n\n if config_data.languages:\n original = original.replace(\n 'LANGUAGE_CODE = \\'en-us\\'', 'LANGUAGE_CODE = \\'{0}\\''.format(config_data.languages[0])\n )\n if config_data.timezone:\n original = original.replace(\n 'TIME_ZONE = \\'UTC\\'', 'TIME_ZONE = \\'{0}\\''.format(config_data.timezone)\n )\n\n for item in overridden_settings:\n if declared_django_version >= LooseVersion('1.9'):\n item_re = re.compile(r'{0} = [^\\]]+\\]'.format(item), re.DOTALL | re.MULTILINE)\n else:\n item_re = re.compile(r'{0} = [^\\)]+\\)'.format(item), re.DOTALL | re.MULTILINE)\n original = item_re.sub('', original)\n # TEMPLATES is special, so custom regexp needed\n if declared_django_version >= LooseVersion('2.0'):\n item_re = re.compile(r'TEMPLATES = .+\\},\\n\\s+\\},\\n]$', re.DOTALL | re.MULTILINE)\n else:\n item_re = re.compile(r'TEMPLATES = .+\\]$', re.DOTALL | re.MULTILINE)\n original = item_re.sub('', original)\n # DATABASES is a dictionary, so different regexp needed\n item_re = re.compile(r'DATABASES = [^\\}]+\\}[^\\}]+\\}', re.DOTALL | re.MULTILINE)\n original = item_re.sub('', original)\n if original.find('SITE_ID') == -1:\n original += 'SITE_ID = 1\\n\\n'\n\n original += _build_settings(config_data)\n # Append extra settings at the end of the file\n original += ('\\n' + extra_settings)\n\n with open(config_data.settings_path, 'w') as fd_dest:\n fd_dest.write(original)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nbuild the django CMS settings dictionary", "response": "def _build_settings(config_data):\n \"\"\"\n Build the django CMS settings dictionary\n\n :param config_data: configuration data\n \"\"\"\n spacer = ' '\n text = []\n vars = get_settings()\n\n vars.MIDDLEWARE_CLASSES.insert(0, vars.APPHOOK_RELOAD_MIDDLEWARE_CLASS)\n\n processors = vars.TEMPLATE_CONTEXT_PROCESSORS + vars.TEMPLATE_CONTEXT_PROCESSORS_3\n text.append(data.TEMPLATES_1_8.format(\n loaders=(',\\n' + spacer * 4).join([\n \"'{0}'\".format(var) for var in vars.TEMPLATE_LOADERS\n if (\n LooseVersion(config_data.django_version) < LooseVersion('2.0') or\n 'eggs' not in var\n )\n ]),\n processors=(',\\n' + spacer * 4).join([\"'{0}'\".format(var) for var in processors]),\n dirs=\"os.path.join(BASE_DIR, '{0}', 'templates'),\".format(config_data.project_name)\n ))\n\n if LooseVersion(config_data.django_version) >= LooseVersion('1.10'):\n text.append('MIDDLEWARE = [\\n{0}{1}\\n]'.format(\n spacer, (',\\n' + spacer).join(['\\'{0}\\''.format(var)\n for var in vars.MIDDLEWARE_CLASSES])\n ))\n else:\n text.append('MIDDLEWARE_CLASSES = [\\n{0}{1}\\n]'.format(\n spacer, (',\\n' + spacer).join([\"'{0}'\".format(var)\n for var in vars.MIDDLEWARE_CLASSES])\n ))\n\n apps = list(vars.INSTALLED_APPS)\n apps = list(vars.CMS_3_HEAD) + apps\n apps.extend(vars.TREEBEARD_APPS)\n apps.extend(vars.CMS_3_APPLICATIONS)\n\n if not config_data.no_plugins:\n apps.extend(vars.FILER_PLUGINS_3)\n\n if config_data.aldryn: # pragma: no cover\n apps.extend(vars.ALDRYN_APPLICATIONS)\n if config_data.reversion and LooseVersion(config_data.cms_version) < LooseVersion('3.4'):\n apps.extend(vars.REVERSION_APPLICATIONS)\n text.append('INSTALLED_APPS = [\\n{0}{1}\\n]'.format(\n spacer, (',\\n' + spacer).join(['\\'{0}\\''.format(var) for var in apps] +\n ['\\'{0}\\''.format(config_data.project_name)])\n ))\n\n text.append('LANGUAGES = (\\n{0}{1}\\n{0}{2}\\n)'.format(\n spacer, '## Customize this',\n ('\\n' + spacer).join(['(\\'{0}\\', gettext(\\'{0}\\')),'.format(item) for item in config_data.languages]) # NOQA\n ))\n\n cms_langs = deepcopy(vars.CMS_LANGUAGES)\n for lang in config_data.languages:\n lang_dict = {'code': lang, 'name': lang}\n lang_dict.update(copy(cms_langs['default']))\n cms_langs[1].append(lang_dict)\n cms_text = ['CMS_LANGUAGES = {']\n cms_text.append('{0}{1}'.format(spacer, '## Customize this'))\n for key, value in iteritems(cms_langs):\n if key == 'default':\n cms_text.append('{0}\\'{1}\\': {{'.format(spacer, key))\n for config_name, config_value in iteritems(value):\n cms_text.append('{0}\\'{1}\\': {2},'.format(spacer * 2, config_name, config_value))\n cms_text.append('{0}}},'.format(spacer))\n else:\n cms_text.append('{0}{1}: ['.format(spacer, key))\n for lang in value:\n cms_text.append('{0}{{'.format(spacer * 2))\n for config_name, config_value in iteritems(lang):\n if config_name == 'code':\n cms_text.append('{0}\\'{1}\\': \\'{2}\\','.format(spacer * 3, config_name, config_value)) # NOQA\n elif config_name == 'name':\n cms_text.append('{0}\\'{1}\\': gettext(\\'{2}\\'),'.format(spacer * 3, config_name, config_value)) # NOQA\n else:\n cms_text.append('{0}\\'{1}\\': {2},'.format(\n spacer * 3, config_name, config_value\n ))\n cms_text.append('{0}}},'.format(spacer * 2))\n cms_text.append('{0}],'.format(spacer))\n cms_text.append('}')\n\n text.append('\\n'.join(cms_text))\n\n if config_data.bootstrap:\n cms_templates = 'CMS_TEMPLATES_BOOTSTRAP'\n else:\n cms_templates = 'CMS_TEMPLATES'\n\n text.append('CMS_TEMPLATES = (\\n{0}{1}\\n{0}{2}\\n)'.format(\n spacer, '## Customize this',\n (',\\n' + spacer).join(\n ['(\\'{0}\\', \\'{1}\\')'.format(*item) for item in getattr(vars, cms_templates)]\n )\n ))\n\n text.append('CMS_PERMISSION = {0}'.format(vars.CMS_PERMISSION))\n text.append('CMS_PLACEHOLDER_CONF = {0}'.format(vars.CMS_PLACEHOLDER_CONF))\n\n database = ['\\'{0}\\': {1}'.format(key, format_val(val)) for key, val in sorted(config_data.db_parsed.items(), key=lambda x: x[0])] # NOQA\n text.append(textwrap.dedent(\"\"\"\n DATABASES = {{\n 'default': {{\n {0}\n }}\n }}\"\"\").strip().format((',\\n' + spacer * 2).join(database))) # NOQA\n\n DJANGO_MIGRATION_MODULES = _detect_migration_layout(vars, apps)\n\n text.append('MIGRATION_MODULES = {{\\n{0}{1}\\n}}'.format(\n spacer, (',\\n' + spacer).join(\n ['\\'{0}\\': \\'{1}\\''.format(*item) for item in DJANGO_MIGRATION_MODULES.items()]\n )\n ))\n\n if config_data.filer:\n text.append('THUMBNAIL_PROCESSORS = (\\n{0}{1}\\n)'.format(\n spacer, (',\\n' + spacer).join(\n ['\\'{0}\\''.format(var) for var in vars.THUMBNAIL_PROCESSORS]\n )\n ))\n return '\\n\\n'.join(text)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nrunning the migrate command to create the database schema", "response": "def setup_database(config_data):\n \"\"\"\n Run the migrate command to create the database schema\n\n :param config_data: configuration data\n \"\"\"\n with chdir(config_data.project_directory):\n env = deepcopy(dict(os.environ))\n env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))\n env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path)))\n commands = []\n\n commands.append(\n [sys.executable, '-W', 'ignore', 'manage.py', 'migrate'],\n )\n\n if config_data.verbose:\n sys.stdout.write(\n 'Database setup commands: {0}\\n'.format(\n ', '.join([' '.join(cmd) for cmd in commands])\n )\n )\n for command in commands:\n try:\n output = subprocess.check_output(\n command, env=env, stderr=subprocess.STDOUT\n )\n sys.stdout.write(output.decode('utf-8'))\n except subprocess.CalledProcessError as e: # pragma: no cover\n if config_data.verbose:\n sys.stdout.write(e.output.decode('utf-8'))\n raise\n\n if not config_data.no_user:\n sys.stdout.write('Creating admin user\\n')\n if config_data.noinput:\n create_user(config_data)\n else:\n subprocess.check_call(' '.join(\n [sys.executable, '-W', 'ignore', 'manage.py', 'createsuperuser']\n ), shell=True, stderr=subprocess.STDOUT)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef create_user(config_data):\n with chdir(os.path.abspath(config_data.project_directory)):\n env = deepcopy(dict(os.environ))\n env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name))\n env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path)))\n subprocess.check_call(\n [sys.executable, 'create_user.py'], env=env, stderr=subprocess.STDOUT\n )\n for ext in ['py', 'pyc']:\n try:\n os.remove('create_user.{0}'.format(ext))\n except OSError:\n pass", "response": "Create admin user with user input"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef sox(args):\n '''Pass an argument list to SoX.\n\n Parameters\n ----------\n args : iterable\n Argument list for SoX. The first item can, but does not\n need to, be 'sox'.\n\n Returns:\n --------\n status : bool\n True on success.\n\n '''\n if args[0].lower() != \"sox\":\n args.insert(0, \"sox\")\n else:\n args[0] = \"sox\"\n\n try:\n logger.info(\"Executing: %s\", ' '.join(args))\n\n process_handle = subprocess.Popen(\n args, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n\n out, err = process_handle.communicate()\n out = out.decode(\"utf-8\")\n err = err.decode(\"utf-8\")\n\n status = process_handle.returncode\n return status, out, err\n\n except OSError as error_msg:\n logger.error(\"OSError: SoX failed! %s\", error_msg)\n except TypeError as error_msg:\n logger.error(\"TypeError: %s\", error_msg)\n return 1, None, None", "response": "Pass an iterable of argument list to SoX."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning a list of audio file formats that can be used with the current install of SoX.", "response": "def _get_valid_formats():\n ''' Calls SoX help for a lists of audio formats available with the current\n install of SoX.\n\n Returns:\n --------\n formats : list\n List of audio file extensions that SoX can process.\n\n '''\n if NO_SOX:\n return []\n\n so = subprocess.check_output(['sox', '-h'])\n if type(so) is not str:\n so = str(so, encoding='UTF-8')\n so = so.split('\\n')\n idx = [i for i in range(len(so)) if 'AUDIO FILE FORMATS:' in so[i]][0]\n formats = so[idx].split(' ')[3:]\n\n return formats"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef soxi(filepath, argument):\n ''' Base call to SoXI.\n\n Parameters\n ----------\n filepath : str\n Path to audio file.\n\n argument : str\n Argument to pass to SoXI.\n\n Returns\n -------\n shell_output : str\n Command line output of SoXI\n '''\n\n if argument not in SOXI_ARGS:\n raise ValueError(\"Invalid argument '{}' to SoXI\".format(argument))\n\n args = ['sox', '--i']\n args.append(\"-{}\".format(argument))\n args.append(filepath)\n\n try:\n shell_output = subprocess.check_output(\n args,\n stderr=subprocess.PIPE\n )\n except CalledProcessError as cpe:\n logger.info(\"SoXI error message: {}\".format(cpe.output))\n raise SoxiError(\"SoXI failed with exit code {}\".format(cpe.returncode))\n\n shell_output = shell_output.decode(\"utf-8\")\n\n return str(shell_output).strip('\\n')", "response": "Base call to SoXI."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\npassing an iterable of argument list to play.", "response": "def play(args):\n '''Pass an argument list to play.\n\n Parameters\n ----------\n args : iterable\n Argument list for play. The first item can, but does not\n need to, be 'play'.\n\n Returns:\n --------\n status : bool\n True on success.\n\n '''\n if args[0].lower() != \"play\":\n args.insert(0, \"play\")\n else:\n args[0] = \"play\"\n\n try:\n logger.info(\"Executing: %s\", \" \".join(args))\n process_handle = subprocess.Popen(\n args, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n\n status = process_handle.wait()\n if process_handle.stderr is not None:\n logger.info(process_handle.stderr)\n\n if status == 0:\n return True\n else:\n logger.info(\"Play returned with error code %s\", status)\n return False\n except OSError as error_msg:\n logger.error(\"OSError: Play failed! %s\", error_msg)\n except TypeError as error_msg:\n logger.error(\"TypeError: %s\", error_msg)\n return False"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nvalidates that combine method can be performed with given files.", "response": "def _validate_file_formats(input_filepath_list, combine_type):\n '''Validate that combine method can be performed with given files.\n Raises IOError if input file formats are incompatible.\n '''\n _validate_sample_rates(input_filepath_list, combine_type)\n\n if combine_type == 'concatenate':\n _validate_num_channels(input_filepath_list, combine_type)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _validate_sample_rates(input_filepath_list, combine_type):\n ''' Check if files in input file list have the same sample rate\n '''\n sample_rates = [\n file_info.sample_rate(f) for f in input_filepath_list\n ]\n if not core.all_equal(sample_rates):\n raise IOError(\n \"Input files do not have the same sample rate. The {} combine \"\n \"type requires that all files have the same sample rate\"\n .format(combine_type)\n )", "response": "Check if all files in input file list have the same sample rate"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _validate_num_channels(input_filepath_list, combine_type):\n ''' Check if files in input file list have the same number of channels\n '''\n channels = [\n file_info.channels(f) for f in input_filepath_list\n ]\n if not core.all_equal(channels):\n raise IOError(\n \"Input files do not have the same number of channels. The \"\n \"{} combine type requires that all files have the same \"\n \"number of channels\"\n .format(combine_type)\n )", "response": "Check if all files in input file list have the same number of channels"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _build_input_format_list(input_filepath_list, input_volumes=None,\n input_format=None):\n '''Set input formats given input_volumes.\n\n Parameters\n ----------\n input_filepath_list : list of str\n List of input files\n input_volumes : list of float, default=None\n List of volumes to be applied upon combining input files. Volumes\n are applied to the input files in order.\n If None, input files will be combined at their original volumes.\n input_format : list of lists, default=None\n List of input formats to be applied to each input file. Formatting\n arguments are applied to the input files in order.\n If None, the input formats will be inferred from the file header.\n\n '''\n n_inputs = len(input_filepath_list)\n input_format_list = []\n for _ in range(n_inputs):\n input_format_list.append([])\n\n # Adjust length of input_volumes list\n if input_volumes is None:\n vols = [1] * n_inputs\n else:\n n_volumes = len(input_volumes)\n if n_volumes < n_inputs:\n logger.warning(\n 'Volumes were only specified for %s out of %s files.'\n 'The last %s files will remain at their original volumes.',\n n_volumes, n_inputs, n_inputs - n_volumes\n )\n vols = input_volumes + [1] * (n_inputs - n_volumes)\n elif n_volumes > n_inputs:\n logger.warning(\n '%s volumes were specified but only %s input files exist.'\n 'The last %s volumes will be ignored.',\n n_volumes, n_inputs, n_volumes - n_inputs\n )\n vols = input_volumes[:n_inputs]\n else:\n vols = [v for v in input_volumes]\n\n # Adjust length of input_format list\n if input_format is None:\n fmts = [[] for _ in range(n_inputs)]\n else:\n n_fmts = len(input_format)\n if n_fmts < n_inputs:\n logger.warning(\n 'Input formats were only specified for %s out of %s files.'\n 'The last %s files will remain unformatted.',\n n_fmts, n_inputs, n_inputs - n_fmts\n )\n fmts = [f for f in input_format]\n fmts.extend([[] for _ in range(n_inputs - n_fmts)])\n elif n_fmts > n_inputs:\n logger.warning(\n '%s Input formats were specified but only %s input files exist'\n '. The last %s formats will be ignored.',\n n_fmts, n_inputs, n_fmts - n_inputs\n )\n fmts = input_format[:n_inputs]\n else:\n fmts = [f for f in input_format]\n\n for i, (vol, fmt) in enumerate(zip(vols, fmts)):\n input_format_list[i].extend(['-v', '{}'.format(vol)])\n input_format_list[i].extend(fmt)\n\n return input_format_list", "response": "Builds the input formats given input_volumes and input_format lists."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _build_input_args(input_filepath_list, input_format_list):\n ''' Builds input arguments by stitching input filepaths and input\n formats together.\n '''\n if len(input_format_list) != len(input_filepath_list):\n raise ValueError(\n \"input_format_list & input_filepath_list are not the same size\"\n )\n\n input_args = []\n zipped = zip(input_filepath_list, input_format_list)\n for input_file, input_fmt in zipped:\n input_args.extend(input_fmt)\n input_args.append(input_file)\n\n return input_args", "response": "Builds input arguments by stitching input filepaths and input_format_list together."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _validate_volumes(input_volumes):\n '''Check input_volumes contains a valid list of volumes.\n\n Parameters\n ----------\n input_volumes : list\n list of volume values. Castable to numbers.\n\n '''\n if not (input_volumes is None or isinstance(input_volumes, list)):\n raise TypeError(\"input_volumes must be None or a list.\")\n\n if isinstance(input_volumes, list):\n for vol in input_volumes:\n if not core.is_number(vol):\n raise ValueError(\n \"Elements of input_volumes must be numbers: found {}\"\n .format(vol)\n )", "response": "Check input_volumes contains a valid list of volumes."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef build(self, input_filepath_list, output_filepath, combine_type,\n input_volumes=None):\n '''Builds the output_file by executing the current set of commands.\n\n Parameters\n ----------\n input_filepath_list : list of str\n List of paths to input audio files.\n output_filepath : str\n Path to desired output file. If a file already exists at the given\n path, the file will be overwritten.\n combine_type : str\n Input file combining method. One of the following values:\n * concatenate : combine input files by concatenating in the\n order given.\n * merge : combine input files by stacking each input file into\n a new channel of the output file.\n * mix : combine input files by summing samples in corresponding\n channels.\n * mix-power : combine input files with volume adjustments such\n that the output volume is roughly equivlent to one of the\n input signals.\n * multiply : combine input files by multiplying samples in\n corresponding samples.\n input_volumes : list of float, default=None\n List of volumes to be applied upon combining input files. Volumes\n are applied to the input files in order.\n If None, input files will be combined at their original volumes.\n\n '''\n file_info.validate_input_file_list(input_filepath_list)\n file_info.validate_output_file(output_filepath)\n _validate_combine_type(combine_type)\n _validate_volumes(input_volumes)\n\n input_format_list = _build_input_format_list(\n input_filepath_list, input_volumes, self.input_format\n )\n\n try:\n _validate_file_formats(input_filepath_list, combine_type)\n except SoxiError:\n logger.warning(\"unable to validate file formats.\")\n\n args = []\n args.extend(self.globals)\n args.extend(['--combine', combine_type])\n\n input_args = _build_input_args(input_filepath_list, input_format_list)\n args.extend(input_args)\n\n args.extend(self.output_format)\n args.append(output_filepath)\n args.extend(self.effects)\n\n status, out, err = sox(args)\n\n if status != 0:\n raise SoxError(\n \"Stdout: {}\\nStderr: {}\".format(out, err)\n )\n else:\n logger.info(\n \"Created %s with combiner %s and effects: %s\",\n output_filepath,\n combine_type,\n \" \".join(self.effects_log)\n )\n if out is not None:\n logger.info(\"[SoX] {}\".format(out))\n return True", "response": "Builds the output_file by executing the current set of commands."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nplays a preview of the output with the current set of effects.", "response": "def preview(self, input_filepath_list, combine_type, input_volumes=None):\n '''Play a preview of the output with the current set of effects\n\n Parameters\n ----------\n input_filepath_list : list of str\n List of paths to input audio files.\n combine_type : str\n Input file combining method. One of the following values:\n * concatenate : combine input files by concatenating in the\n order given.\n * merge : combine input files by stacking each input file into\n a new channel of the output file.\n * mix : combine input files by summing samples in corresponding\n channels.\n * mix-power : combine input files with volume adjustments such\n that the output volume is roughly equivlent to one of the\n input signals.\n * multiply : combine input files by multiplying samples in\n corresponding samples.\n input_volumes : list of float, default=None\n List of volumes to be applied upon combining input files. Volumes\n are applied to the input files in order.\n If None, input files will be combined at their original volumes.\n\n '''\n args = [\"play\", \"--no-show-progress\"]\n args.extend(self.globals)\n args.extend(['--combine', combine_type])\n\n input_format_list = _build_input_format_list(\n input_filepath_list, input_volumes, self.input_format\n )\n input_args = _build_input_args(input_filepath_list, input_format_list)\n args.extend(input_args)\n args.extend(self.effects)\n\n play(args)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nsets input file format arguments. This is primarily useful when dealing with audio files without a file extension. Overwrites any previously set input file arguments. If this function is not explicity called the input format is inferred from the file extension or the file's header. Parameters ---------- file_type : list of str or None, default=None The file type of the input audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : list of float or None, default=None The sample rate of the input audio file. If None the sample rate is inferred. bits : list of int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : list of int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : list of str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (\u2018two\u2019s complement\u2019) integers. Commonly used with a 16 or 24\u2212bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (\u2018real\u2019) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. \u03bc-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world\u2019s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM\u2019s original 13kbps \u2018Full Rate\u2019 audio format. It is usually CPU-intensive to work with GSM audio. ignore_length : list of bool or None, default=None If True, overrides an (incorrect) audio length given in an audio file\u2019s header. If this option is given then SoX will keep reading audio until it reaches the end of the input file.", "response": "def set_input_format(self, file_type=None, rate=None, bits=None,\n channels=None, encoding=None, ignore_length=None):\n '''Sets input file format arguments. This is primarily useful when\n dealing with audio files without a file extension. Overwrites any\n previously set input file arguments.\n\n If this function is not explicity called the input format is inferred\n from the file extension or the file's header.\n\n Parameters\n ----------\n file_type : list of str or None, default=None\n The file type of the input audio file. Should be the same as what\n the file extension would be, for ex. 'mp3' or 'wav'.\n rate : list of float or None, default=None\n The sample rate of the input audio file. If None the sample rate\n is inferred.\n bits : list of int or None, default=None\n The number of bits per sample. If None, the number of bits per\n sample is inferred.\n channels : list of int or None, default=None\n The number of channels in the audio file. If None the number of\n channels is inferred.\n encoding : list of str or None, default=None\n The audio encoding type. Sometimes needed with file-types that\n support more than one encoding type. One of:\n * signed-integer : PCM data stored as signed (\u2018two\u2019s\n complement\u2019) integers. Commonly used with a 16 or 24\u2212bit\n encoding size. A value of 0 represents minimum signal\n power.\n * unsigned-integer : PCM data stored as unsigned integers.\n Commonly used with an 8-bit encoding size. A value of 0\n represents maximum signal power.\n * floating-point : PCM data stored as IEEE 753 single precision\n (32-bit) or double precision (64-bit) floating-point\n (\u2018real\u2019) numbers. A value of 0 represents minimum signal\n power.\n * a-law : International telephony standard for logarithmic\n encoding to 8 bits per sample. It has a precision\n equivalent to roughly 13-bit PCM and is sometimes encoded\n with reversed bit-ordering.\n * u-law : North American telephony standard for logarithmic\n encoding to 8 bits per sample. A.k.a. \u03bc-law. It has a\n precision equivalent to roughly 14-bit PCM and is sometimes\n encoded with reversed bit-ordering.\n * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM;\n it has a precision equivalent to roughly 12-bit PCM. ADPCM\n is a form of audio compression that has a good compromise\n between audio quality and encoding/decoding speed.\n * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision\n equivalent to roughly 13-bit PCM.\n * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision\n equivalent to roughly 14-bit PCM.\n * gsm-full-rate : GSM is currently used for the vast majority\n of the world\u2019s digital wireless telephone calls. It\n utilises several audio formats with different bit-rates and\n associated speech quality. SoX has support for GSM\u2019s\n original 13kbps \u2018Full Rate\u2019 audio format. It is usually\n CPU-intensive to work with GSM audio.\n ignore_length : list of bool or None, default=None\n If True, overrides an (incorrect) audio length given in an audio\n file\u2019s header. If this option is given then SoX will keep reading\n audio until it reaches the end of the input file.\n\n '''\n if file_type is not None and not isinstance(file_type, list):\n raise ValueError(\"file_type must be a list or None.\")\n\n if file_type is not None:\n if not all([f in VALID_FORMATS for f in file_type]):\n raise ValueError(\n 'file_type elements '\n 'must be one of {}'.format(VALID_FORMATS)\n )\n else:\n file_type = []\n\n if rate is not None and not isinstance(rate, list):\n raise ValueError(\"rate must be a list or None.\")\n\n if rate is not None:\n if not all([is_number(r) and r > 0 for r in rate]):\n raise ValueError('rate elements must be positive floats.')\n else:\n rate = []\n\n if bits is not None and not isinstance(bits, list):\n raise ValueError(\"bits must be a list or None.\")\n\n if bits is not None:\n if not all([isinstance(b, int) and b > 0 for b in bits]):\n raise ValueError('bit elements must be positive ints.')\n else:\n bits = []\n\n if channels is not None and not isinstance(channels, list):\n raise ValueError(\"channels must be a list or None.\")\n\n if channels is not None:\n if not all([isinstance(c, int) and c > 0 for c in channels]):\n raise ValueError('channel elements must be positive ints.')\n else:\n channels = []\n\n if encoding is not None and not isinstance(encoding, list):\n raise ValueError(\"encoding must be a list or None.\")\n\n if encoding is not None:\n if not all([e in ENCODING_VALS for e in encoding]):\n raise ValueError(\n 'elements of encoding must '\n 'be one of {}'.format(ENCODING_VALS)\n )\n else:\n encoding = []\n\n if ignore_length is not None and not isinstance(ignore_length, list):\n raise ValueError(\"ignore_length must be a list or None.\")\n\n if ignore_length is not None:\n if not all([isinstance(l, bool) for l in ignore_length]):\n raise ValueError(\"ignore_length elements must be booleans.\")\n else:\n ignore_length = []\n\n max_input_arg_len = max([\n len(file_type), len(rate), len(bits), len(channels),\n len(encoding), len(ignore_length)\n ])\n\n input_format = []\n for _ in range(max_input_arg_len):\n input_format.append([])\n\n for i, f in enumerate(file_type):\n input_format[i].extend(['-t', '{}'.format(f)])\n\n for i, r in enumerate(rate):\n input_format[i].extend(['-r', '{}'.format(r)])\n\n for i, b in enumerate(bits):\n input_format[i].extend(['-b', '{}'.format(b)])\n\n for i, c in enumerate(channels):\n input_format[i].extend(['-c', '{}'.format(c)])\n\n for i, e in enumerate(encoding):\n input_format[i].extend(['-e', '{}'.format(e)])\n\n for i, l in enumerate(ignore_length):\n if l is True:\n input_format[i].append('--ignore-length')\n\n self.input_format = input_format\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the bitrate of the audio file at the specified filepath.", "response": "def bitrate(input_filepath):\n '''\n Number of bits per sample (0 if not applicable).\n\n Parameters\n ----------\n input_filepath : str\n Path to audio file.\n\n Returns\n -------\n bitrate : int\n number of bits per sample\n returns 0 if not applicable\n '''\n validate_input_file(input_filepath)\n output = soxi(input_filepath, 'b')\n if output == '0':\n logger.warning(\"Bitrate unavailable for %s\", input_filepath)\n return int(output)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef duration(input_filepath):\n '''\n Show duration in seconds (0 if unavailable).\n\n Parameters\n ----------\n input_filepath : str\n Path to audio file.\n\n Returns\n -------\n duration : float\n Duration of audio file in seconds.\n If unavailable or empty, returns 0.\n '''\n validate_input_file(input_filepath)\n output = soxi(input_filepath, 'D')\n if output == '0':\n logger.warning(\"Duration unavailable for %s\", input_filepath)\n\n return float(output)", "response": "Show duration in seconds."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nshows number of samples in audio file.", "response": "def num_samples(input_filepath):\n '''\n Show number of samples (0 if unavailable).\n\n Parameters\n ----------\n input_filepath : str\n Path to audio file.\n\n Returns\n -------\n n_samples : int\n total number of samples in audio file.\n Returns 0 if empty or unavailable\n '''\n validate_input_file(input_filepath)\n output = soxi(input_filepath, 's')\n if output == '0':\n logger.warning(\"Number of samples unavailable for %s\", input_filepath)\n return int(output)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef silent(input_filepath, threshold=0.001):\n '''\n Determine if an input file is silent.\n\n Parameters\n ----------\n input_filepath : str\n The input filepath.\n threshold : float\n Threshold for determining silence\n\n Returns\n -------\n is_silent : bool\n True if file is determined silent.\n '''\n validate_input_file(input_filepath)\n stat_dictionary = stat(input_filepath)\n mean_norm = stat_dictionary['Mean norm']\n if mean_norm is not float('nan'):\n if mean_norm >= threshold:\n return False\n else:\n return True\n else:\n return True", "response": "Determines if an input file is silent."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ninputs file validation function. Checks that input file exists and can be processed by SoX.", "response": "def validate_input_file(input_filepath):\n '''Input file validation function. Checks that file exists and can be\n processed by SoX.\n\n Parameters\n ----------\n input_filepath : str\n The input filepath.\n\n '''\n if not os.path.exists(input_filepath):\n raise IOError(\n \"input_filepath {} does not exist.\".format(input_filepath)\n )\n ext = file_extension(input_filepath)\n if ext not in VALID_FORMATS:\n logger.info(\"Valid formats: %s\", \" \".join(VALID_FORMATS))\n logger.warning(\n \"This install of SoX cannot process .{} files.\".format(ext)\n )"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ninput file list validation function. Checks that input file list contains valid filepaths that can be processed by SoX.", "response": "def validate_input_file_list(input_filepath_list):\n '''Input file list validation function. Checks that object is a list and\n contains valid filepaths that can be processed by SoX.\n\n Parameters\n ----------\n input_filepath_list : list\n A list of filepaths.\n\n '''\n if not isinstance(input_filepath_list, list):\n raise TypeError(\"input_filepath_list must be a list.\")\n elif len(input_filepath_list) < 2:\n raise ValueError(\"input_filepath_list must have at least 2 files.\")\n\n for input_filepath in input_filepath_list:\n validate_input_file(input_filepath)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef validate_output_file(output_filepath):\n '''Output file validation function. Checks that file can be written, and\n has a valid file extension. Throws a warning if the path already exists,\n as it will be overwritten on build.\n\n Parameters\n ----------\n output_filepath : str\n The output filepath.\n\n Returns:\n --------\n output_filepath : str\n The output filepath.\n\n '''\n\n nowrite_conditions = [\n bool(os.path.dirname(output_filepath)) or\\\n not os.access(os.getcwd(), os.W_OK),\n not os.access(os.path.dirname(output_filepath), os.W_OK)]\n\n if all(nowrite_conditions):\n raise IOError(\n \"SoX cannot write to output_filepath {}\".format(output_filepath)\n )\n\n ext = file_extension(output_filepath)\n if ext not in VALID_FORMATS:\n logger.info(\"Valid formats: %s\", \" \".join(VALID_FORMATS))\n logger.warning(\n \"This install of SoX cannot process .{} files.\".format(ext)\n )\n\n if os.path.exists(output_filepath):\n logger.warning(\n 'output_file: %s already exists and will be overwritten on build',\n output_filepath\n )", "response": "Output file validation function. Checks that file can be written and that the output filepath is a valid file extension."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngets a dictionary of file information.", "response": "def info(filepath):\n '''Get a dictionary of file information\n\n Parameters\n ----------\n filepath : str\n File path.\n\n Returns:\n --------\n info_dictionary : dict\n Dictionary of file information. Fields are:\n * channels\n * sample_rate\n * bitrate\n * duration\n * num_samples\n * encoding\n * silent\n '''\n info_dictionary = {\n 'channels': channels(filepath),\n 'sample_rate': sample_rate(filepath),\n 'bitrate': bitrate(filepath),\n 'duration': duration(filepath),\n 'num_samples': num_samples(filepath),\n 'encoding': encoding(filepath),\n 'silent': silent(filepath)\n }\n return info_dictionary"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _stat_call(filepath):\n '''Call sox's stat function.\n\n Parameters\n ----------\n filepath : str\n File path.\n\n Returns\n -------\n stat_output : str\n Sox output from stderr.\n '''\n validate_input_file(filepath)\n args = ['sox', filepath, '-n', 'stat']\n _, _, stat_output = sox(args)\n return stat_output", "response": "Call sox s stat function."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef _parse_stat(stat_output):\n '''Parse the string output from sox's stat function\n\n Parameters\n ----------\n stat_output : str\n Sox output from stderr.\n\n Returns\n -------\n stat_dictionary : dict\n Dictionary of audio statistics.\n '''\n lines = stat_output.split('\\n')\n stat_dict = {}\n for line in lines:\n split_line = line.split(':')\n if len(split_line) == 2:\n key = split_line[0]\n val = split_line[1].strip(' ')\n try:\n val = float(val)\n except ValueError:\n val = None\n stat_dict[key] = val\n\n return stat_dict", "response": "Parse the string output from sox s stat function\n "}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef set_globals(self, dither=False, guard=False, multithread=False,\n replay_gain=False, verbosity=2):\n '''Sets SoX's global arguments.\n Overwrites any previously set global arguments.\n If this function is not explicity called, globals are set to this\n function's defaults.\n\n Parameters\n ----------\n dither : bool, default=False\n If True, dithering is applied for low files with low bit rates.\n guard : bool, default=False\n If True, invokes the gain effect to guard against clipping.\n multithread : bool, default=False\n If True, each channel is processed in parallel.\n replay_gain : bool, default=False\n If True, applies replay-gain adjustment to input-files.\n verbosity : int, default=2\n SoX's verbosity level. One of:\n * 0 : No messages are shown at all\n * 1 : Only error messages are shown. These are generated if SoX\n cannot complete the requested commands.\n * 2 : Warning messages are also shown. These are generated if\n SoX can complete the requested commands, but not exactly\n according to the requested command parameters, or if\n clipping occurs.\n * 3 : Descriptions of SoX\u2019s processing phases are also shown.\n Useful for seeing exactly how SoX is processing your audio.\n * 4, >4 : Messages to help with debugging SoX are also shown.\n\n '''\n if not isinstance(dither, bool):\n raise ValueError('dither must be a boolean.')\n\n if not isinstance(guard, bool):\n raise ValueError('guard must be a boolean.')\n\n if not isinstance(multithread, bool):\n raise ValueError('multithread must be a boolean.')\n\n if not isinstance(replay_gain, bool):\n raise ValueError('replay_gain must be a boolean.')\n\n if verbosity not in VERBOSITY_VALS:\n raise ValueError(\n 'Invalid value for VERBOSITY. Must be one {}'.format(\n VERBOSITY_VALS)\n )\n\n global_args = []\n\n if not dither:\n global_args.append('-D')\n\n if guard:\n global_args.append('-G')\n\n if multithread:\n global_args.append('--multi-threaded')\n\n if replay_gain:\n global_args.append('--replay-gain')\n global_args.append('track')\n\n global_args.append('-V{}'.format(verbosity))\n\n self.globals = global_args\n return self", "response": "Sets the global arguments for the given instance of the class."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef set_input_format(self, file_type=None, rate=None, bits=None,\n channels=None, encoding=None, ignore_length=False):\n '''Sets input file format arguments. This is primarily useful when\n dealing with audio files without a file extension. Overwrites any\n previously set input file arguments.\n\n If this function is not explicity called the input format is inferred\n from the file extension or the file's header.\n\n Parameters\n ----------\n file_type : str or None, default=None\n The file type of the input audio file. Should be the same as what\n the file extension would be, for ex. 'mp3' or 'wav'.\n rate : float or None, default=None\n The sample rate of the input audio file. If None the sample rate\n is inferred.\n bits : int or None, default=None\n The number of bits per sample. If None, the number of bits per\n sample is inferred.\n channels : int or None, default=None\n The number of channels in the audio file. If None the number of\n channels is inferred.\n encoding : str or None, default=None\n The audio encoding type. Sometimes needed with file-types that\n support more than one encoding type. One of:\n * signed-integer : PCM data stored as signed (\u2018two\u2019s\n complement\u2019) integers. Commonly used with a 16 or 24\u2212bit\n encoding size. A value of 0 represents minimum signal\n power.\n * unsigned-integer : PCM data stored as unsigned integers.\n Commonly used with an 8-bit encoding size. A value of 0\n represents maximum signal power.\n * floating-point : PCM data stored as IEEE 753 single precision\n (32-bit) or double precision (64-bit) floating-point\n (\u2018real\u2019) numbers. A value of 0 represents minimum signal\n power.\n * a-law : International telephony standard for logarithmic\n encoding to 8 bits per sample. It has a precision\n equivalent to roughly 13-bit PCM and is sometimes encoded\n with reversed bit-ordering.\n * u-law : North American telephony standard for logarithmic\n encoding to 8 bits per sample. A.k.a. \u03bc-law. It has a\n precision equivalent to roughly 14-bit PCM and is sometimes\n encoded with reversed bit-ordering.\n * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM;\n it has a precision equivalent to roughly 12-bit PCM. ADPCM\n is a form of audio compression that has a good compromise\n between audio quality and encoding/decoding speed.\n * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision\n equivalent to roughly 13-bit PCM.\n * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision\n equivalent to roughly 14-bit PCM.\n * gsm-full-rate : GSM is currently used for the vast majority\n of the world\u2019s digital wireless telephone calls. It\n utilises several audio formats with different bit-rates and\n associated speech quality. SoX has support for GSM\u2019s\n original 13kbps \u2018Full Rate\u2019 audio format. It is usually\n CPU-intensive to work with GSM audio.\n ignore_length : bool, default=False\n If True, overrides an (incorrect) audio length given in an audio\n file\u2019s header. If this option is given then SoX will keep reading\n audio until it reaches the end of the input file.\n\n '''\n if file_type not in VALID_FORMATS + [None]:\n raise ValueError(\n 'Invalid file_type. Must be one of {}'.format(VALID_FORMATS)\n )\n\n if not is_number(rate) and rate is not None:\n raise ValueError('rate must be a float or None')\n\n if rate is not None and rate <= 0:\n raise ValueError('rate must be a positive number')\n\n if not isinstance(bits, int) and bits is not None:\n raise ValueError('bits must be an int or None')\n\n if bits is not None and bits <= 0:\n raise ValueError('bits must be a positive number')\n\n if not isinstance(channels, int) and channels is not None:\n raise ValueError('channels must be an int or None')\n\n if channels is not None and channels <= 0:\n raise ValueError('channels must be a positive number')\n\n if encoding not in ENCODING_VALS + [None]:\n raise ValueError(\n 'Invalid encoding. Must be one of {}'.format(ENCODING_VALS)\n )\n\n if not isinstance(ignore_length, bool):\n raise ValueError('ignore_length must be a boolean')\n\n input_format = []\n\n if file_type is not None:\n input_format.extend(['-t', '{}'.format(file_type)])\n\n if rate is not None:\n input_format.extend(['-r', '{:f}'.format(rate)])\n\n if bits is not None:\n input_format.extend(['-b', '{}'.format(bits)])\n\n if channels is not None:\n input_format.extend(['-c', '{}'.format(channels)])\n\n if encoding is not None:\n input_format.extend(['-e', '{}'.format(encoding)])\n\n if ignore_length:\n input_format.append('--ignore-length')\n\n self.input_format = input_format\n return self", "response": "This function sets the input file format arguments. This is primarily useful when dealing with audio files with a file extension."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef set_output_format(self, file_type=None, rate=None, bits=None,\n channels=None, encoding=None, comments=None,\n append_comments=True):\n '''Sets output file format arguments. These arguments will overwrite\n any format related arguments supplied by other effects (e.g. rate).\n\n If this function is not explicity called the output format is inferred\n from the file extension or the file's header.\n\n Parameters\n ----------\n file_type : str or None, default=None\n The file type of the output audio file. Should be the same as what\n the file extension would be, for ex. 'mp3' or 'wav'.\n rate : float or None, default=None\n The sample rate of the output audio file. If None the sample rate\n is inferred.\n bits : int or None, default=None\n The number of bits per sample. If None, the number of bits per\n sample is inferred.\n channels : int or None, default=None\n The number of channels in the audio file. If None the number of\n channels is inferred.\n encoding : str or None, default=None\n The audio encoding type. Sometimes needed with file-types that\n support more than one encoding type. One of:\n * signed-integer : PCM data stored as signed (\u2018two\u2019s\n complement\u2019) integers. Commonly used with a 16 or 24\u2212bit\n encoding size. A value of 0 represents minimum signal\n power.\n * unsigned-integer : PCM data stored as unsigned integers.\n Commonly used with an 8-bit encoding size. A value of 0\n represents maximum signal power.\n * floating-point : PCM data stored as IEEE 753 single precision\n (32-bit) or double precision (64-bit) floating-point\n (\u2018real\u2019) numbers. A value of 0 represents minimum signal\n power.\n * a-law : International telephony standard for logarithmic\n encoding to 8 bits per sample. It has a precision\n equivalent to roughly 13-bit PCM and is sometimes encoded\n with reversed bit-ordering.\n * u-law : North American telephony standard for logarithmic\n encoding to 8 bits per sample. A.k.a. \u03bc-law. It has a\n precision equivalent to roughly 14-bit PCM and is sometimes\n encoded with reversed bit-ordering.\n * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM;\n it has a precision equivalent to roughly 12-bit PCM. ADPCM\n is a form of audio compression that has a good compromise\n between audio quality and encoding/decoding speed.\n * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision\n equivalent to roughly 13-bit PCM.\n * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision\n equivalent to roughly 14-bit PCM.\n * gsm-full-rate : GSM is currently used for the vast majority\n of the world\u2019s digital wireless telephone calls. It\n utilises several audio formats with different bit-rates and\n associated speech quality. SoX has support for GSM\u2019s\n original 13kbps \u2018Full Rate\u2019 audio format. It is usually\n CPU-intensive to work with GSM audio.\n comments : str or None, default=None\n If not None, the string is added as a comment in the header of the\n output audio file. If None, no comments are added.\n append_comments : bool, default=True\n If True, comment strings are appended to SoX's default comments. If\n False, the supplied comment replaces the existing comment.\n\n '''\n if file_type not in VALID_FORMATS + [None]:\n raise ValueError(\n 'Invalid file_type. Must be one of {}'.format(VALID_FORMATS)\n )\n\n if not is_number(rate) and rate is not None:\n raise ValueError('rate must be a float or None')\n\n if rate is not None and rate <= 0:\n raise ValueError('rate must be a positive number')\n\n if not isinstance(bits, int) and bits is not None:\n raise ValueError('bits must be an int or None')\n\n if bits is not None and bits <= 0:\n raise ValueError('bits must be a positive number')\n\n if not isinstance(channels, int) and channels is not None:\n raise ValueError('channels must be an int or None')\n\n if channels is not None and channels <= 0:\n raise ValueError('channels must be a positive number')\n\n if encoding not in ENCODING_VALS + [None]:\n raise ValueError(\n 'Invalid encoding. Must be one of {}'.format(ENCODING_VALS)\n )\n\n if comments is not None and not isinstance(comments, str):\n raise ValueError('comments must be a string or None')\n\n if not isinstance(append_comments, bool):\n raise ValueError('append_comments must be a boolean')\n\n output_format = []\n\n if file_type is not None:\n output_format.extend(['-t', '{}'.format(file_type)])\n\n if rate is not None:\n output_format.extend(['-r', '{:f}'.format(rate)])\n\n if bits is not None:\n output_format.extend(['-b', '{}'.format(bits)])\n\n if channels is not None:\n output_format.extend(['-c', '{}'.format(channels)])\n\n if encoding is not None:\n output_format.extend(['-e', '{}'.format(encoding)])\n\n if comments is not None:\n if append_comments:\n output_format.extend(['--add-comment', comments])\n else:\n output_format.extend(['--comment', comments])\n\n self.output_format = output_format\n return self", "response": "Set the output format of the log file."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef build(self, input_filepath, output_filepath, extra_args=None,\n return_output=False):\n '''Builds the output_file by executing the current set of commands.\n\n Parameters\n ----------\n input_filepath : str\n Path to input audio file.\n output_filepath : str or None\n Path to desired output file. If a file already exists at the given\n path, the file will be overwritten.\n If None, no file will be created.\n extra_args : list or None, default=None\n If a list is given, these additional arguments are passed to SoX\n at the end of the list of effects.\n Don't use this argument unless you know exactly what you're doing!\n return_output : bool, default=False\n If True, returns the status and information sent to stderr and\n stdout as a tuple (status, stdout, stderr).\n Otherwise returns True on success.\n\n '''\n file_info.validate_input_file(input_filepath)\n\n if output_filepath is not None:\n file_info.validate_output_file(output_filepath)\n else:\n output_filepath = '-n'\n\n if input_filepath == output_filepath:\n raise ValueError(\n \"input_filepath must be different from output_filepath.\"\n )\n\n args = []\n args.extend(self.globals)\n args.extend(self.input_format)\n args.append(input_filepath)\n args.extend(self.output_format)\n args.append(output_filepath)\n args.extend(self.effects)\n\n if extra_args is not None:\n if not isinstance(extra_args, list):\n raise ValueError(\"extra_args must be a list.\")\n args.extend(extra_args)\n\n status, out, err = sox(args)\n\n if status != 0:\n raise SoxError(\n \"Stdout: {}\\nStderr: {}\".format(out, err)\n )\n else:\n logger.info(\n \"Created %s with effects: %s\",\n output_filepath,\n \" \".join(self.effects_log)\n )\n if out is not None:\n logger.info(\"[SoX] {}\".format(out))\n\n if return_output:\n return status, out, err\n else:\n return True", "response": "Builds the output_file by executing the current set of commands."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nplay a preview of the output with the current set of effects.", "response": "def preview(self, input_filepath):\n '''Play a preview of the output with the current set of effects\n\n Parameters\n ----------\n input_filepath : str\n Path to input audio file.\n\n '''\n args = [\"play\", \"--no-show-progress\"]\n args.extend(self.globals)\n args.extend(self.input_format)\n args.append(input_filepath)\n args.extend(self.effects)\n\n play(args)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\napplying a two - qubit all - pass filter.", "response": "def allpass(self, frequency, width_q=2.0):\n '''Apply a two-pole all-pass filter. An all-pass filter changes the\n audio\u2019s frequency to phase relationship without changing its frequency\n to amplitude relationship. The filter is described in detail in at\n http://musicdsp.org/files/Audio-EQ-Cookbook.txt\n\n Parameters\n ----------\n frequency : float\n The filter's center frequency in Hz.\n width_q : float, default=2.0\n The filter's width as a Q-factor.\n\n See Also\n --------\n equalizer, highpass, lowpass, sinc\n\n '''\n if not is_number(frequency) or frequency <= 0:\n raise ValueError(\"frequency must be a positive number.\")\n\n if not is_number(width_q) or width_q <= 0:\n raise ValueError(\"width_q must be a positive number.\")\n\n effect_args = [\n 'allpass', '{:f}'.format(frequency), '{:f}q'.format(width_q)\n ]\n\n self.effects.extend(effect_args)\n self.effects_log.append('allpass')\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\napplying a two - pole Butterworth band - pass filter with the given central frequency and band - width.", "response": "def bandpass(self, frequency, width_q=2.0, constant_skirt=False):\n '''Apply a two-pole Butterworth band-pass filter with the given central\n frequency, and (3dB-point) band-width. The filter rolls off at 6dB per\n octave (20dB per decade) and is described in detail in\n http://musicdsp.org/files/Audio-EQ-Cookbook.txt\n\n Parameters\n ----------\n frequency : float\n The filter's center frequency in Hz.\n width_q : float, default=2.0\n The filter's width as a Q-factor.\n constant_skirt : bool, default=False\n If True, selects constant skirt gain (peak gain = width_q).\n If False, selects constant 0dB peak gain.\n\n See Also\n --------\n bandreject, sinc\n\n '''\n if not is_number(frequency) or frequency <= 0:\n raise ValueError(\"frequency must be a positive number.\")\n\n if not is_number(width_q) or width_q <= 0:\n raise ValueError(\"width_q must be a positive number.\")\n\n if not isinstance(constant_skirt, bool):\n raise ValueError(\"constant_skirt must be a boolean.\")\n\n effect_args = ['bandpass']\n\n if constant_skirt:\n effect_args.append('-c')\n\n effect_args.extend(['{:f}'.format(frequency), '{:f}q'.format(width_q)])\n\n self.effects.extend(effect_args)\n self.effects_log.append('bandpass')\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef bend(self, n_bends, start_times, end_times, cents, frame_rate=25,\n oversample_rate=16):\n '''Changes pitch by specified amounts at specified times.\n The pitch-bending algorithm utilises the Discrete Fourier Transform\n (DFT) at a particular frame rate and over-sampling rate.\n\n Parameters\n ----------\n n_bends : int\n The number of intervals to pitch shift\n start_times : list of floats\n A list of absolute start times (in seconds), in order\n end_times : list of floats\n A list of absolute end times (in seconds) in order.\n [start_time, end_time] intervals may not overlap!\n cents : list of floats\n A list of pitch shifts in cents. A positive value shifts the pitch\n up, a negative value shifts the pitch down.\n frame_rate : int, default=25\n The number of DFT frames to process per second, between 10 and 80\n oversample_rate: int, default=16\n The number of frames to over sample per second, between 4 and 32\n\n See Also\n --------\n pitch\n\n '''\n if not isinstance(n_bends, int) or n_bends < 1:\n raise ValueError(\"n_bends must be a positive integer.\")\n\n if not isinstance(start_times, list) or len(start_times) != n_bends:\n raise ValueError(\"start_times must be a list of length n_bends.\")\n\n if any([(not is_number(p) or p <= 0) for p in start_times]):\n raise ValueError(\"start_times must be positive floats.\")\n\n if sorted(start_times) != start_times:\n raise ValueError(\"start_times must be in increasing order.\")\n\n if not isinstance(end_times, list) or len(end_times) != n_bends:\n raise ValueError(\"end_times must be a list of length n_bends.\")\n\n if any([(not is_number(p) or p <= 0) for p in end_times]):\n raise ValueError(\"end_times must be positive floats.\")\n\n if sorted(end_times) != end_times:\n raise ValueError(\"end_times must be in increasing order.\")\n\n if any([e <= s for s, e in zip(start_times, end_times)]):\n raise ValueError(\n \"end_times must be element-wise greater than start_times.\"\n )\n\n if any([e > s for s, e in zip(start_times[1:], end_times[:-1])]):\n raise ValueError(\n \"[start_time, end_time] intervals must be non-overlapping.\"\n )\n\n if not isinstance(cents, list) or len(cents) != n_bends:\n raise ValueError(\"cents must be a list of length n_bends.\")\n\n if any([not is_number(p) for p in cents]):\n raise ValueError(\"elements of cents must be floats.\")\n\n if (not isinstance(frame_rate, int) or\n frame_rate < 10 or frame_rate > 80):\n raise ValueError(\"frame_rate must be an integer between 10 and 80\")\n\n if (not isinstance(oversample_rate, int) or\n oversample_rate < 4 or oversample_rate > 32):\n raise ValueError(\n \"oversample_rate must be an integer between 4 and 32.\"\n )\n\n effect_args = [\n 'bend',\n '-f', '{}'.format(frame_rate),\n '-o', '{}'.format(oversample_rate)\n ]\n\n last = 0\n for i in range(n_bends):\n t_start = round(start_times[i] - last, 2)\n t_end = round(end_times[i] - start_times[i], 2)\n effect_args.append(\n '{:f},{:f},{:f}'.format(t_start, cents[i], t_end)\n )\n last = end_times[i]\n\n self.effects.extend(effect_args)\n self.effects_log.append('bend')\n return self", "response": "This function changes pitch by specified amounts at specified times."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef biquad(self, b, a):\n '''Apply a biquad IIR filter with the given coefficients.\n\n Parameters\n ----------\n b : list of floats\n Numerator coefficients. Must be length 3\n a : list of floats\n Denominator coefficients. Must be length 3\n\n See Also\n --------\n fir, treble, bass, equalizer\n\n '''\n if not isinstance(b, list):\n raise ValueError('b must be a list.')\n\n if not isinstance(a, list):\n raise ValueError('a must be a list.')\n\n if len(b) != 3:\n raise ValueError('b must be a length 3 list.')\n\n if len(a) != 3:\n raise ValueError('a must be a length 3 list.')\n\n if not all([is_number(b_val) for b_val in b]):\n raise ValueError('all elements of b must be numbers.')\n\n if not all([is_number(a_val) for a_val in a]):\n raise ValueError('all elements of a must be numbers.')\n\n effect_args = [\n 'biquad', '{:f}'.format(b[0]), '{:f}'.format(b[1]),\n '{:f}'.format(b[2]), '{:f}'.format(a[0]),\n '{:f}'.format(a[1]), '{:f}'.format(a[2])\n ]\n\n self.effects.extend(effect_args)\n self.effects_log.append('biquad')\n return self", "response": "Apply a biquad IIR filter with the given coefficients."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef channels(self, n_channels):\n '''Change the number of channels in the audio signal. If decreasing the\n number of channels it mixes channels together, if increasing the number\n of channels it duplicates.\n\n Note: This overrides arguments used in the convert effect!\n\n Parameters\n ----------\n n_channels : int\n Desired number of channels.\n\n See Also\n --------\n convert\n\n '''\n if not isinstance(n_channels, int) or n_channels <= 0:\n raise ValueError('n_channels must be a positive integer.')\n\n effect_args = ['channels', '{}'.format(n_channels)]\n\n self.effects.extend(effect_args)\n self.effects_log.append('channels')\n return self", "response": "Change the number of channels in the audio signal."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef chorus(self, gain_in=0.5, gain_out=0.9, n_voices=3, delays=None,\n decays=None, speeds=None, depths=None, shapes=None):\n '''Add a chorus effect to the audio. This can makeasingle vocal sound\n like a chorus, but can also be applied to instrumentation.\n\n Chorus resembles an echo effect with a short delay, but whereas with\n echo the delay is constant, with chorus, it is varied using sinusoidal\n or triangular modulation. The modulation depth defines the range the\n modulated delay is played before or after the delay. Hence the delayed\n sound will sound slower or faster, that is the delayed sound tuned\n around the original one, like in a chorus where some vocals are\n slightly off key.\n\n Parameters\n ----------\n gain_in : float, default=0.3\n The time in seconds over which the instantaneous level of the input\n signal is averaged to determine increases in volume.\n gain_out : float, default=0.8\n The time in seconds over which the instantaneous level of the input\n signal is averaged to determine decreases in volume.\n n_voices : int, default=3\n The number of voices in the chorus effect.\n delays : list of floats > 20 or None, default=None\n If a list, the list of delays (in miliseconds) of length n_voices.\n If None, the individual delay parameters are chosen automatically\n to be between 40 and 60 miliseconds.\n decays : list of floats or None, default=None\n If a list, the list of decays (as a fraction of gain_in) of length\n n_voices.\n If None, the individual decay parameters are chosen automatically\n to be between 0.3 and 0.4.\n speeds : list of floats or None, default=None\n If a list, the list of modulation speeds (in Hz) of length n_voices\n If None, the individual speed parameters are chosen automatically\n to be between 0.25 and 0.4 Hz.\n depths : list of floats or None, default=None\n If a list, the list of depths (in miliseconds) of length n_voices.\n If None, the individual delay parameters are chosen automatically\n to be between 1 and 3 miliseconds.\n shapes : list of 's' or 't' or None, deault=None\n If a list, the list of modulation shapes - 's' for sinusoidal or\n 't' for triangular - of length n_voices.\n If None, the individual shapes are chosen automatically.\n\n '''\n if not is_number(gain_in) or gain_in <= 0 or gain_in > 1:\n raise ValueError(\"gain_in must be a number between 0 and 1.\")\n if not is_number(gain_out) or gain_out <= 0 or gain_out > 1:\n raise ValueError(\"gain_out must be a number between 0 and 1.\")\n if not isinstance(n_voices, int) or n_voices <= 0:\n raise ValueError(\"n_voices must be a positive integer.\")\n\n # validate delays\n if not (delays is None or isinstance(delays, list)):\n raise ValueError(\"delays must be a list or None\")\n if delays is not None:\n if len(delays) != n_voices:\n raise ValueError(\"the length of delays must equal n_voices\")\n if any((not is_number(p) or p < 20) for p in delays):\n raise ValueError(\"the elements of delays must be numbers > 20\")\n else:\n delays = [random.uniform(40, 60) for _ in range(n_voices)]\n\n # validate decays\n if not (decays is None or isinstance(decays, list)):\n raise ValueError(\"decays must be a list or None\")\n if decays is not None:\n if len(decays) != n_voices:\n raise ValueError(\"the length of decays must equal n_voices\")\n if any((not is_number(p) or p <= 0 or p > 1) for p in decays):\n raise ValueError(\n \"the elements of decays must be between 0 and 1\"\n )\n else:\n decays = [random.uniform(0.3, 0.4) for _ in range(n_voices)]\n\n # validate speeds\n if not (speeds is None or isinstance(speeds, list)):\n raise ValueError(\"speeds must be a list or None\")\n if speeds is not None:\n if len(speeds) != n_voices:\n raise ValueError(\"the length of speeds must equal n_voices\")\n if any((not is_number(p) or p <= 0) for p in speeds):\n raise ValueError(\"the elements of speeds must be numbers > 0\")\n else:\n speeds = [random.uniform(0.25, 0.4) for _ in range(n_voices)]\n\n # validate depths\n if not (depths is None or isinstance(depths, list)):\n raise ValueError(\"depths must be a list or None\")\n if depths is not None:\n if len(depths) != n_voices:\n raise ValueError(\"the length of depths must equal n_voices\")\n if any((not is_number(p) or p <= 0) for p in depths):\n raise ValueError(\"the elements of depths must be numbers > 0\")\n else:\n depths = [random.uniform(1.0, 3.0) for _ in range(n_voices)]\n\n # validate shapes\n if not (shapes is None or isinstance(shapes, list)):\n raise ValueError(\"shapes must be a list or None\")\n if shapes is not None:\n if len(shapes) != n_voices:\n raise ValueError(\"the length of shapes must equal n_voices\")\n if any((p not in ['t', 's']) for p in shapes):\n raise ValueError(\"the elements of shapes must be 's' or 't'\")\n else:\n shapes = [random.choice(['t', 's']) for _ in range(n_voices)]\n\n effect_args = ['chorus', '{}'.format(gain_in), '{}'.format(gain_out)]\n\n for i in range(n_voices):\n effect_args.extend([\n '{:f}'.format(delays[i]),\n '{:f}'.format(decays[i]),\n '{:f}'.format(speeds[i]),\n '{:f}'.format(depths[i]),\n '-{}'.format(shapes[i])\n ])\n\n self.effects.extend(effect_args)\n self.effects_log.append('chorus')\n return self", "response": "Add a chorus effect to the audio."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nconvert output audio to the specified format.", "response": "def convert(self, samplerate=None, n_channels=None, bitdepth=None):\n '''Converts output audio to the specified format.\n\n Parameters\n ----------\n samplerate : float, default=None\n Desired samplerate. If None, defaults to the same as input.\n n_channels : int, default=None\n Desired number of channels. If None, defaults to the same as input.\n bitdepth : int, default=None\n Desired bitdepth. If None, defaults to the same as input.\n\n See Also\n --------\n rate\n\n '''\n bitdepths = [8, 16, 24, 32, 64]\n if bitdepth is not None:\n if bitdepth not in bitdepths:\n raise ValueError(\n \"bitdepth must be one of {}.\".format(str(bitdepths))\n )\n self.output_format.extend(['-b', '{}'.format(bitdepth)])\n if n_channels is not None:\n if not isinstance(n_channels, int) or n_channels <= 0:\n raise ValueError(\n \"n_channels must be a positive integer.\"\n )\n self.output_format.extend(['-c', '{}'.format(n_channels)])\n if samplerate is not None:\n if not is_number(samplerate) or samplerate <= 0:\n raise ValueError(\"samplerate must be a positive number.\")\n self.rate(samplerate)\n return self"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\napply a DC shift to the audio.", "response": "def dcshift(self, shift=0.0):\n '''Apply a DC shift to the audio.\n\n Parameters\n ----------\n shift : float\n Amount to shift audio between -2 and 2. (Audio is between -1 and 1)\n\n See Also\n --------\n highpass\n\n '''\n if not is_number(shift) or shift < -2 or shift > 2:\n raise ValueError('shift must be a number between -2 and 2.')\n\n effect_args = ['dcshift', '{:f}'.format(shift)]\n\n self.effects.extend(effect_args)\n self.effects_log.append('dcshift')\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef deemph(self):\n '''Apply Compact Disc (IEC 60908) de-emphasis (a treble attenuation\n shelving filter). Pre-emphasis was applied in the mastering of some\n CDs issued in the early 1980s. These included many classical music\n albums, as well as now sought-after issues of albums by The Beatles,\n Pink Floyd and others. Pre-emphasis should be removed at playback time\n by a de-emphasis filter in the playback device. However, not all modern\n CD players have this filter, and very few PC CD drives have it; playing\n pre-emphasised audio without the correct de-emphasis filter results in\n audio that sounds harsh and is far from what its creators intended.\n\n The de-emphasis filter is implemented as a biquad and requires the\n input audio sample rate to be either 44.1kHz or 48kHz. Maximum\n deviation from the ideal response is only 0.06dB (up to 20kHz).\n\n See Also\n --------\n bass, treble\n '''\n effect_args = ['deemph']\n\n self.effects.extend(effect_args)\n self.effects_log.append('deemph')\n return self", "response": "Apply Compact Disc ( IEC 60908 ) de - emphasis filter to the current time - store."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndelaying one or more audio channels such that they start at the given positions.", "response": "def delay(self, positions):\n '''Delay one or more audio channels such that they start at the given\n positions.\n\n Parameters\n ----------\n positions: list of floats\n List of times (in seconds) to delay each audio channel.\n If fewer positions are given than the number of channels, the\n remaining channels will be unaffected.\n\n '''\n if not isinstance(positions, list):\n raise ValueError(\"positions must be a a list of numbers\")\n\n if not all((is_number(p) and p >= 0) for p in positions):\n raise ValueError(\"positions must be positive nubmers\")\n\n effect_args = ['delay']\n effect_args.extend(['{:f}'.format(p) for p in positions])\n\n self.effects.extend(effect_args)\n self.effects_log.append('delay')\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef earwax(self):\n '''Makes audio easier to listen to on headphones. Adds \u2018cues\u2019 to 44.1kHz\n stereo audio so that when listened to on headphones the stereo image is\n moved from inside your head (standard for headphones) to outside and in\n front of the listener (standard for speakers).\n\n Warning: Will only work properly on 44.1kHz stereo audio!\n\n '''\n effect_args = ['earwax']\n\n self.effects.extend(effect_args)\n self.effects_log.append('earwax')\n return self", "response": "Makes audio easier to listen to on headphones. Adds \u2018cues\u2019 to 44. 1kHz\n stereo audio so that when listened to on headphones the stereo image is moved to outside of the headphones."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nadd echoing to the audio.", "response": "def echo(self, gain_in=0.8, gain_out=0.9, n_echos=1, delays=[60],\n decays=[0.4]):\n '''Add echoing to the audio.\n\n Echoes are reflected sound and can occur naturally amongst mountains\n (and sometimes large buildings) when talking or shouting; digital echo\n effects emulate this behav- iour and are often used to help fill out\n the sound of a single instrument or vocal. The time differ- ence\n between the original signal and the reflection is the 'delay' (time),\n and the loudness of the reflected signal is the 'decay'. Multiple\n echoes can have different delays and decays.\n\n Parameters\n ----------\n gain_in : float, default=0.8\n Input volume, between 0 and 1\n gain_out : float, default=0.9\n Output volume, between 0 and 1\n n_echos : int, default=1\n Number of reflections\n delays : list, default=[60]\n List of delays in miliseconds\n decays : list, default=[0.4]\n List of decays, relative to gain in between 0 and 1\n\n See Also\n --------\n echos, reverb, chorus\n '''\n if not is_number(gain_in) or gain_in <= 0 or gain_in > 1:\n raise ValueError(\"gain_in must be a number between 0 and 1.\")\n\n if not is_number(gain_out) or gain_out <= 0 or gain_out > 1:\n raise ValueError(\"gain_out must be a number between 0 and 1.\")\n\n if not isinstance(n_echos, int) or n_echos <= 0:\n raise ValueError(\"n_echos must be a positive integer.\")\n\n # validate delays\n if not isinstance(delays, list):\n raise ValueError(\"delays must be a list\")\n\n if len(delays) != n_echos:\n raise ValueError(\"the length of delays must equal n_echos\")\n\n if any((not is_number(p) or p <= 0) for p in delays):\n raise ValueError(\"the elements of delays must be numbers > 0\")\n\n # validate decays\n if not isinstance(decays, list):\n raise ValueError(\"decays must be a list\")\n\n if len(decays) != n_echos:\n raise ValueError(\"the length of decays must equal n_echos\")\n if any((not is_number(p) or p <= 0 or p > 1) for p in decays):\n raise ValueError(\n \"the elements of decays must be between 0 and 1\"\n )\n\n effect_args = ['echo', '{:f}'.format(gain_in), '{:f}'.format(gain_out)]\n\n for i in range(n_echos):\n effect_args.extend([\n '{}'.format(delays[i]),\n '{}'.format(decays[i])\n ])\n\n self.effects.extend(effect_args)\n self.effects_log.append('echo')\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\napplying a two - pole peaking equalisation filter to boost or reduce around a given frequency.", "response": "def equalizer(self, frequency, width_q, gain_db):\n '''Apply a two-pole peaking equalisation (EQ) filter to boost or\n reduce around a given frequency.\n This effect can be applied multiple times to produce complex EQ curves.\n\n Parameters\n ----------\n frequency : float\n The filter's central frequency in Hz.\n width_q : float\n The filter's width as a Q-factor.\n gain_db : float\n The filter's gain in dB.\n\n See Also\n --------\n bass, treble\n\n '''\n if not is_number(frequency) or frequency <= 0:\n raise ValueError(\"frequency must be a positive number.\")\n\n if not is_number(width_q) or width_q <= 0:\n raise ValueError(\"width_q must be a positive number.\")\n\n if not is_number(gain_db):\n raise ValueError(\"gain_db must be a number.\")\n\n effect_args = [\n 'equalizer',\n '{:f}'.format(frequency),\n '{:f}q'.format(width_q),\n '{:f}'.format(gain_db)\n ]\n self.effects.extend(effect_args)\n self.effects_log.append('equalizer')\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef fade(self, fade_in_len=0.0, fade_out_len=0.0, fade_shape='q'):\n '''Add a fade in and/or fade out to an audio file.\n Default fade shape is 1/4 sine wave.\n\n Parameters\n ----------\n fade_in_len : float, default=0.0\n Length of fade-in (seconds). If fade_in_len = 0,\n no fade in is applied.\n fade_out_len : float, defaut=0.0\n Length of fade-out (seconds). If fade_out_len = 0,\n no fade in is applied.\n fade_shape : str, default='q'\n Shape of fade. Must be one of\n * 'q' for quarter sine (default),\n * 'h' for half sine,\n * 't' for linear,\n * 'l' for logarithmic\n * 'p' for inverted parabola.\n\n See Also\n --------\n splice\n\n '''\n fade_shapes = ['q', 'h', 't', 'l', 'p']\n if fade_shape not in fade_shapes:\n raise ValueError(\n \"Fade shape must be one of {}\".format(\" \".join(fade_shapes))\n )\n if not is_number(fade_in_len) or fade_in_len < 0:\n raise ValueError(\"fade_in_len must be a nonnegative number.\")\n if not is_number(fade_out_len) or fade_out_len < 0:\n raise ValueError(\"fade_out_len must be a nonnegative number.\")\n\n effect_args = []\n\n if fade_in_len > 0:\n effect_args.extend([\n 'fade', '{}'.format(fade_shape), '{:f}'.format(fade_in_len)\n ])\n\n if fade_out_len > 0:\n effect_args.extend([\n 'reverse', 'fade', '{}'.format(fade_shape),\n '{:f}'.format(fade_out_len), 'reverse'\n ])\n\n if len(effect_args) > 0:\n self.effects.extend(effect_args)\n self.effects_log.append('fade')\n\n return self", "response": "Add a fade in and fade out to an audio file."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nusing SoX\u2019s FFT convolution engine with given FIR filter coefficients.", "response": "def fir(self, coefficients):\n '''Use SoX\u2019s FFT convolution engine with given FIR filter coefficients.\n\n Parameters\n ----------\n coefficients : list\n fir filter coefficients\n\n '''\n if not isinstance(coefficients, list):\n raise ValueError(\"coefficients must be a list.\")\n\n if not all([is_number(c) for c in coefficients]):\n raise ValueError(\"coefficients must be numbers.\")\n\n effect_args = ['fir']\n effect_args.extend(['{:f}'.format(c) for c in coefficients])\n\n self.effects.extend(effect_args)\n self.effects_log.append('fir')\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef flanger(self, delay=0, depth=2, regen=0, width=71, speed=0.5,\n shape='sine', phase=25, interp='linear'):\n '''Apply a flanging effect to the audio.\n\n Parameters\n ----------\n delay : float, default=0\n Base delay (in miliseconds) between 0 and 30.\n depth : float, default=2\n Added swept delay (in miliseconds) between 0 and 10.\n regen : float, default=0\n Percentage regeneration between -95 and 95.\n width : float, default=71,\n Percentage of delayed signal mixed with original between 0 and 100.\n speed : float, default=0.5\n Sweeps per second (in Hz) between 0.1 and 10.\n shape : 'sine' or 'triangle', default='sine'\n Swept wave shape\n phase : float, default=25\n Swept wave percentage phase-shift for multi-channel flange between\n 0 and 100. 0 = 100 = same phase on each channel\n interp : 'linear' or 'quadratic', default='linear'\n Digital delay-line interpolation type.\n\n See Also\n --------\n tremolo\n '''\n if not is_number(delay) or delay < 0 or delay > 30:\n raise ValueError(\"delay must be a number between 0 and 30.\")\n if not is_number(depth) or depth < 0 or depth > 10:\n raise ValueError(\"depth must be a number between 0 and 10.\")\n if not is_number(regen) or regen < -95 or regen > 95:\n raise ValueError(\"regen must be a number between -95 and 95.\")\n if not is_number(width) or width < 0 or width > 100:\n raise ValueError(\"width must be a number between 0 and 100.\")\n if not is_number(speed) or speed < 0.1 or speed > 10:\n raise ValueError(\"speed must be a number between 0.1 and 10.\")\n if shape not in ['sine', 'triangle']:\n raise ValueError(\"shape must be one of 'sine' or 'triangle'.\")\n if not is_number(phase) or phase < 0 or phase > 100:\n raise ValueError(\"phase must be a number between 0 and 100.\")\n if interp not in ['linear', 'quadratic']:\n raise ValueError(\"interp must be one of 'linear' or 'quadratic'.\")\n\n effect_args = [\n 'flanger',\n '{:f}'.format(delay),\n '{:f}'.format(depth),\n '{:f}'.format(regen),\n '{:f}'.format(width),\n '{:f}'.format(speed),\n '{}'.format(shape),\n '{:f}'.format(phase),\n '{}'.format(interp)\n ]\n\n self.effects.extend(effect_args)\n self.effects_log.append('flanger')\n\n return self", "response": "Apply a flanging effect to the audio."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef gain(self, gain_db=0.0, normalize=True, limiter=False, balance=None):\n '''Apply amplification or attenuation to the audio signal.\n\n Parameters\n ----------\n gain_db : float, default=0.0\n Gain adjustment in decibels (dB).\n normalize : bool, default=True\n If True, audio is normalized to gain_db relative to full scale.\n If False, simply adjusts the audio power level by gain_db.\n limiter : bool, default=False\n If True, a simple limiter is invoked to prevent clipping.\n balance : str or None, default=None\n Balance gain across channels. Can be one of:\n * None applies no balancing (default)\n * 'e' applies gain to all channels other than that with the\n highest peak level, such that all channels attain the same\n peak level\n * 'B' applies gain to all channels other than that with the\n highest RMS level, such that all channels attain the same\n RMS level\n * 'b' applies gain with clipping protection to all channels other\n than that with the highest RMS level, such that all channels\n attain the same RMS level\n If normalize=True, 'B' and 'b' are equivalent.\n\n See Also\n --------\n loudness\n\n '''\n if not is_number(gain_db):\n raise ValueError(\"gain_db must be a number.\")\n\n if not isinstance(normalize, bool):\n raise ValueError(\"normalize must be a boolean.\")\n\n if not isinstance(limiter, bool):\n raise ValueError(\"limiter must be a boolean.\")\n\n if balance not in [None, 'e', 'B', 'b']:\n raise ValueError(\"balance must be one of None, 'e', 'B', or 'b'.\")\n\n effect_args = ['gain']\n\n if balance is not None:\n effect_args.append('-{}'.format(balance))\n\n if normalize:\n effect_args.append('-n')\n\n if limiter:\n effect_args.append('-l')\n\n effect_args.append('{:f}'.format(gain_db))\n self.effects.extend(effect_args)\n self.effects_log.append('gain')\n\n return self", "response": "Applies amplification or attenuation to the audio signal."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\napplying a high - pass filter to the log file.", "response": "def highpass(self, frequency, width_q=0.707, n_poles=2):\n '''Apply a high-pass filter with 3dB point frequency. The filter can be\n either single-pole or double-pole. The filters roll off at 6dB per pole\n per octave (20dB per pole per decade).\n\n Parameters\n ----------\n frequency : float\n The filter's cutoff frequency in Hz.\n width_q : float, default=0.707\n The filter's width as a Q-factor. Applies only when n_poles=2.\n The default gives a Butterworth response.\n n_poles : int, default=2\n The number of poles in the filter. Must be either 1 or 2\n\n See Also\n --------\n lowpass, equalizer, sinc, allpass\n\n '''\n if not is_number(frequency) or frequency <= 0:\n raise ValueError(\"frequency must be a positive number.\")\n\n if not is_number(width_q) or width_q <= 0:\n raise ValueError(\"width_q must be a positive number.\")\n\n if n_poles not in [1, 2]:\n raise ValueError(\"n_poles must be 1 or 2.\")\n\n effect_args = [\n 'highpass', '-{}'.format(n_poles), '{:f}'.format(frequency)\n ]\n\n if n_poles == 2:\n effect_args.append('{:f}q'.format(width_q))\n\n self.effects.extend(effect_args)\n self.effects_log.append('highpass')\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef hilbert(self, num_taps=None):\n '''Apply an odd-tap Hilbert transform filter, phase-shifting the signal\n by 90 degrees. This is used in many matrix coding schemes and for\n analytic signal generation. The process is often written as a\n multiplication by i (or j), the imaginary unit. An odd-tap Hilbert\n transform filter has a bandpass characteristic, attenuating the lowest\n and highest frequencies.\n\n Parameters\n ----------\n num_taps : int or None, default=None\n Number of filter taps - must be odd. If none, it is chosen to have\n a cutoff frequency of about 75 Hz.\n\n '''\n if num_taps is not None and not isinstance(num_taps, int):\n raise ValueError(\"num taps must be None or an odd integer.\")\n\n if num_taps is not None and num_taps % 2 == 0:\n raise ValueError(\"num_taps must an odd integer.\")\n\n effect_args = ['hilbert']\n\n if num_taps is not None:\n effect_args.extend(['-n', '{}'.format(num_taps)])\n\n self.effects.extend(effect_args)\n self.effects_log.append('hilbert')\n\n return self", "response": "Apply an odd - tap Hilbert transform filter to the signal\n ."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef loudness(self, gain_db=-10.0, reference_level=65.0):\n '''Loudness control. Similar to the gain effect, but provides\n equalisation for the human auditory system.\n\n The gain is adjusted by gain_db and the signal is equalised according\n to ISO 226 w.r.t. reference_level.\n\n Parameters\n ----------\n gain_db : float, default=-10.0\n Loudness adjustment amount (in dB)\n reference_level : float, default=65.0\n Reference level (in dB) according to which the signal is equalized.\n Must be between 50 and 75 (dB)\n\n See Also\n --------\n gain\n\n '''\n if not is_number(gain_db):\n raise ValueError('gain_db must be a number.')\n\n if not is_number(reference_level):\n raise ValueError('reference_level must be a number')\n\n if reference_level > 75 or reference_level < 50:\n raise ValueError('reference_level must be between 50 and 75')\n\n effect_args = [\n 'loudness',\n '{:f}'.format(gain_db),\n '{:f}'.format(reference_level)\n ]\n self.effects.extend(effect_args)\n self.effects_log.append('loudness')\n\n return self", "response": "Add a loudness control to the log."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncalculate a profile of the audio for use in noise reduction.", "response": "def noiseprof(self, input_filepath, profile_path):\n '''Calculate a profile of the audio for use in noise reduction.\n Running this command does not effect the Transformer effects\n chain. When this function is called, the calculated noise profile\n file is saved to the `profile_path`.\n\n Parameters\n ----------\n input_filepath : str\n Path to audiofile from which to compute a noise profile.\n profile_path : str\n Path to save the noise profile file.\n\n See Also\n --------\n noisered\n\n '''\n if os.path.isdir(profile_path):\n raise ValueError(\n \"profile_path {} is a directory.\".format(profile_path))\n\n if os.path.dirname(profile_path) == '' and profile_path != '':\n _abs_profile_path = os.path.join(os.getcwd(), profile_path)\n else:\n _abs_profile_path = profile_path\n\n if not os.access(os.path.dirname(_abs_profile_path), os.W_OK):\n raise IOError(\n \"profile_path {} is not writeable.\".format(_abs_profile_path))\n\n effect_args = ['noiseprof', profile_path]\n self.build(input_filepath, None, extra_args=effect_args)\n\n return None"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef noisered(self, profile_path, amount=0.5):\n '''Reduce noise in the audio signal by profiling and filtering.\n This effect is moderately effective at removing consistent\n background noise such as hiss or hum.\n\n Parameters\n ----------\n profile_path : str\n Path to a noise profile file.\n This file can be generated using the `noiseprof` effect.\n amount : float, default=0.5\n How much noise should be removed is specified by amount. Should\n be between 0 and 1. Higher numbers will remove more noise but\n present a greater likelihood of removing wanted components of\n the audio signal.\n\n See Also\n --------\n noiseprof\n\n '''\n\n if not os.path.exists(profile_path):\n raise IOError(\n \"profile_path {} does not exist.\".format(profile_path))\n\n if not is_number(amount) or amount < 0 or amount > 1:\n raise ValueError(\"amount must be a number between 0 and 1.\")\n\n effect_args = [\n 'noisered',\n profile_path,\n '{:f}'.format(amount)\n ]\n self.effects.extend(effect_args)\n self.effects_log.append('noisered')\n\n return self", "response": "Reduce noise in the audio signal by profiling and filtering."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef norm(self, db_level=-3.0):\n '''Normalize an audio file to a particular db level.\n This behaves identically to the gain effect with normalize=True.\n\n Parameters\n ----------\n db_level : float, default=-3.0\n Output volume (db)\n\n See Also\n --------\n gain, loudness\n\n '''\n if not is_number(db_level):\n raise ValueError('db_level must be a number.')\n\n effect_args = [\n 'norm',\n '{:f}'.format(db_level)\n ]\n self.effects.extend(effect_args)\n self.effects_log.append('norm')\n\n return self", "response": "Normalize an audio file to a particular db level."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef oops(self):\n '''Out Of Phase Stereo effect. Mixes stereo to twin-mono where each\n mono channel contains the difference between the left and right stereo\n channels. This is sometimes known as the 'karaoke' effect as it often\n has the effect of removing most or all of the vocals from a recording.\n\n '''\n effect_args = ['oops']\n self.effects.extend(effect_args)\n self.effects_log.append('oops')\n\n return self", "response": "Out Of Phase Stereo effect. Mixes stereo to twin - mono where each\n mono channel contains the difference between the left and right stereo\n channels."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\napplies non - linear distortion.", "response": "def overdrive(self, gain_db=20.0, colour=20.0):\n '''Apply non-linear distortion.\n\n Parameters\n ----------\n gain_db : float, default=20\n Controls the amount of distortion (dB).\n colour : float, default=20\n Controls the amount of even harmonic content in the output (dB).\n\n '''\n if not is_number(gain_db):\n raise ValueError('db_level must be a number.')\n\n if not is_number(colour):\n raise ValueError('colour must be a number.')\n\n effect_args = [\n 'overdrive',\n '{:f}'.format(gain_db),\n '{:f}'.format(colour)\n ]\n self.effects.extend(effect_args)\n self.effects_log.append('overdrive')\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nadding silence to the beginning or end of a file.", "response": "def pad(self, start_duration=0.0, end_duration=0.0):\n '''Add silence to the beginning or end of a file.\n Calling this with the default arguments has no effect.\n\n Parameters\n ----------\n start_duration : float\n Number of seconds of silence to add to beginning.\n end_duration : float\n Number of seconds of silence to add to end.\n\n See Also\n --------\n delay\n\n '''\n if not is_number(start_duration) or start_duration < 0:\n raise ValueError(\"Start duration must be a positive number.\")\n\n if not is_number(end_duration) or end_duration < 0:\n raise ValueError(\"End duration must be positive.\")\n\n effect_args = [\n 'pad',\n '{:f}'.format(start_duration),\n '{:f}'.format(end_duration)\n ]\n self.effects.extend(effect_args)\n self.effects_log.append('pad')\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\napplying a phaser effect to the audio.", "response": "def phaser(self, gain_in=0.8, gain_out=0.74, delay=3, decay=0.4, speed=0.5,\n modulation_shape='sinusoidal'):\n '''Apply a phasing effect to the audio.\n\n Parameters\n ----------\n gain_in : float, default=0.8\n Input volume between 0 and 1\n gain_out: float, default=0.74\n Output volume between 0 and 1\n delay : float, default=3\n Delay in miliseconds between 0 and 5\n decay : float, default=0.4\n Decay relative to gain_in, between 0.1 and 0.5.\n speed : float, default=0.5\n Modulation speed in Hz, between 0.1 and 2\n modulation_shape : str, defaul='sinusoidal'\n Modulation shpae. One of 'sinusoidal' or 'triangular'\n\n See Also\n --------\n flanger, tremolo\n '''\n if not is_number(gain_in) or gain_in <= 0 or gain_in > 1:\n raise ValueError(\"gain_in must be a number between 0 and 1.\")\n\n if not is_number(gain_out) or gain_out <= 0 or gain_out > 1:\n raise ValueError(\"gain_out must be a number between 0 and 1.\")\n\n if not is_number(delay) or delay <= 0 or delay > 5:\n raise ValueError(\"delay must be a positive number.\")\n\n if not is_number(decay) or decay < 0.1 or decay > 0.5:\n raise ValueError(\"decay must be a number between 0.1 and 0.5.\")\n\n if not is_number(speed) or speed < 0.1 or speed > 2:\n raise ValueError(\"speed must be a positive number.\")\n\n if modulation_shape not in ['sinusoidal', 'triangular']:\n raise ValueError(\n \"modulation_shape must be one of 'sinusoidal', 'triangular'.\"\n )\n\n effect_args = [\n 'phaser',\n '{:f}'.format(gain_in),\n '{:f}'.format(gain_out),\n '{:f}'.format(delay),\n '{:f}'.format(decay),\n '{:f}'.format(speed)\n ]\n\n if modulation_shape == 'sinusoidal':\n effect_args.append('-s')\n elif modulation_shape == 'triangular':\n effect_args.append('-t')\n\n self.effects.extend(effect_args)\n self.effects_log.append('phaser')\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\npitch shift the audio without changing the tempo.", "response": "def pitch(self, n_semitones, quick=False):\n '''Pitch shift the audio without changing the tempo.\n\n This effect uses the WSOLA algorithm. The audio is chopped up into\n segments which are then shifted in the time domain and overlapped\n (cross-faded) at points where their waveforms are most similar as\n determined by measurement of least squares.\n\n Parameters\n ----------\n n_semitones : float\n The number of semitones to shift. Can be positive or negative.\n quick : bool, default=False\n If True, this effect will run faster but with lower sound quality.\n\n See Also\n --------\n bend, speed, tempo\n\n '''\n if not is_number(n_semitones):\n raise ValueError(\"n_semitones must be a positive number\")\n\n if n_semitones < -12 or n_semitones > 12:\n logger.warning(\n \"Using an extreme pitch shift. \"\n \"Quality of results will be poor\"\n )\n\n if not isinstance(quick, bool):\n raise ValueError(\"quick must be a boolean.\")\n\n effect_args = ['pitch']\n\n if quick:\n effect_args.append('-q')\n\n effect_args.append('{:f}'.format(n_semitones * 100.))\n\n self.effects.extend(effect_args)\n self.effects_log.append('pitch')\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef rate(self, samplerate, quality='h'):\n '''Change the audio sampling rate (i.e. resample the audio) to any\n given `samplerate`. Better the resampling quality = slower runtime.\n\n Parameters\n ----------\n samplerate : float\n Desired sample rate.\n quality : str\n Resampling quality. One of:\n * q : Quick - very low quality,\n * l : Low,\n * m : Medium,\n * h : High (default),\n * v : Very high\n\n See Also\n --------\n upsample, downsample, convert\n\n '''\n quality_vals = ['q', 'l', 'm', 'h', 'v']\n if not is_number(samplerate) or samplerate <= 0:\n raise ValueError(\"Samplerate must be a positive number.\")\n\n if quality not in quality_vals:\n raise ValueError(\n \"Quality must be one of {}.\".format(' '.join(quality_vals))\n )\n\n effect_args = [\n 'rate',\n '-{}'.format(quality),\n '{:f}'.format(samplerate)\n ]\n self.effects.extend(effect_args)\n self.effects_log.append('rate')\n\n return self", "response": "Change the audio sampling rate to any ArcGIS resource."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nrepeat the entire audio count times.", "response": "def repeat(self, count=1):\n '''Repeat the entire audio count times.\n\n Parameters\n ----------\n count : int, default=1\n The number of times to repeat the audio.\n\n '''\n if not isinstance(count, int) or count < 1:\n raise ValueError(\"count must be a postive integer.\")\n\n effect_args = ['repeat', '{}'.format(count)]\n self.effects.extend(effect_args)\n self.effects_log.append('repeat')"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef reverb(self, reverberance=50, high_freq_damping=50, room_scale=100,\n stereo_depth=100, pre_delay=0, wet_gain=0, wet_only=False):\n '''Add reverberation to the audio using the \u2018freeverb\u2019 algorithm.\n A reverberation effect is sometimes desirable for concert halls that\n are too small or contain so many people that the hall\u2019s natural\n reverberance is diminished. Applying a small amount of stereo reverb\n to a (dry) mono signal will usually make it sound more natural.\n\n Parameters\n ----------\n reverberance : float, default=50\n Percentage of reverberance\n high_freq_damping : float, default=50\n Percentage of high-frequency damping.\n room_scale : float, default=100\n Scale of the room as a percentage.\n stereo_depth : float, default=100\n Stereo depth as a percentage.\n pre_delay : float, default=0\n Pre-delay in milliseconds.\n wet_gain : float, default=0\n Amount of wet gain in dB\n wet_only : bool, default=False\n If True, only outputs the wet signal.\n\n See Also\n --------\n echo\n\n '''\n\n if (not is_number(reverberance) or reverberance < 0 or\n reverberance > 100):\n raise ValueError(\"reverberance must be between 0 and 100\")\n\n if (not is_number(high_freq_damping) or high_freq_damping < 0 or\n high_freq_damping > 100):\n raise ValueError(\"high_freq_damping must be between 0 and 100\")\n\n if (not is_number(room_scale) or room_scale < 0 or\n room_scale > 100):\n raise ValueError(\"room_scale must be between 0 and 100\")\n\n if (not is_number(stereo_depth) or stereo_depth < 0 or\n stereo_depth > 100):\n raise ValueError(\"stereo_depth must be between 0 and 100\")\n\n if not is_number(pre_delay) or pre_delay < 0:\n raise ValueError(\"pre_delay must be a positive number\")\n\n if not is_number(wet_gain):\n raise ValueError(\"wet_gain must be a number\")\n\n if not isinstance(wet_only, bool):\n raise ValueError(\"wet_only must be a boolean.\")\n\n effect_args = ['reverb']\n\n if wet_only:\n effect_args.append('-w')\n\n effect_args.extend([\n '{:f}'.format(reverberance),\n '{:f}'.format(high_freq_damping),\n '{:f}'.format(room_scale),\n '{:f}'.format(stereo_depth),\n '{:f}'.format(pre_delay),\n '{:f}'.format(wet_gain)\n ])\n\n self.effects.extend(effect_args)\n self.effects_log.append('reverb')\n\n return self", "response": "Add a reverberation effect to the audio using the \u2018freeverb\u2019 algorithm."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef reverse(self):\n '''Reverse the audio completely\n '''\n effect_args = ['reverse']\n self.effects.extend(effect_args)\n self.effects_log.append('reverse')\n\n return self", "response": "Reverse the audio completely\n "}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef silence(self, location=0, silence_threshold=0.1,\n min_silence_duration=0.1, buffer_around_silence=False):\n '''Removes silent regions from an audio file.\n\n Parameters\n ----------\n location : int, default=0\n Where to remove silence. One of:\n * 0 to remove silence throughout the file (default),\n * 1 to remove silence from the beginning,\n * -1 to remove silence from the end,\n silence_threshold : float, default=0.1\n Silence threshold as percentage of maximum sample amplitude.\n Must be between 0 and 100.\n min_silence_duration : float, default=0.1\n The minimum ammount of time in seconds required for a region to be\n considered non-silent.\n buffer_around_silence : bool, default=False\n If True, leaves a buffer of min_silence_duration around removed\n silent regions.\n\n See Also\n --------\n vad\n\n '''\n if location not in [-1, 0, 1]:\n raise ValueError(\"location must be one of -1, 0, 1.\")\n\n if not is_number(silence_threshold) or silence_threshold < 0:\n raise ValueError(\n \"silence_threshold must be a number between 0 and 100\"\n )\n elif silence_threshold >= 100:\n raise ValueError(\n \"silence_threshold must be a number between 0 and 100\"\n )\n\n if not is_number(min_silence_duration) or min_silence_duration <= 0:\n raise ValueError(\n \"min_silence_duration must be a positive number.\"\n )\n\n if not isinstance(buffer_around_silence, bool):\n raise ValueError(\"buffer_around_silence must be a boolean.\")\n\n effect_args = []\n\n if location == -1:\n effect_args.append('reverse')\n\n if buffer_around_silence:\n effect_args.extend(['silence', '-l'])\n else:\n effect_args.append('silence')\n\n effect_args.extend([\n '1',\n '{:f}'.format(min_silence_duration),\n '{:f}%'.format(silence_threshold)\n ])\n\n if location == 0:\n effect_args.extend([\n '-1',\n '{:f}'.format(min_silence_duration),\n '{:f}%'.format(silence_threshold)\n ])\n\n if location == -1:\n effect_args.append('reverse')\n\n self.effects.extend(effect_args)\n self.effects_log.append('silence')\n\n return self", "response": "Removes silent regions from an audio file."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\napply a sinc kaiser - windowed low - pass low - pass or band - reject filter to the signal.", "response": "def sinc(self, filter_type='high', cutoff_freq=3000,\n stop_band_attenuation=120, transition_bw=None,\n phase_response=None):\n '''Apply a sinc kaiser-windowed low-pass, high-pass, band-pass, or\n band-reject filter to the signal.\n\n Parameters\n ----------\n filter_type : str, default='high'\n Type of filter. One of:\n - 'high' for a high-pass filter\n - 'low' for a low-pass filter\n - 'pass' for a band-pass filter\n - 'reject' for a band-reject filter\n cutoff_freq : float or list, default=3000\n A scalar or length 2 list indicating the filter's critical\n frequencies. The critical frequencies are given in Hz and must be\n positive. For a high-pass or low-pass filter, cutoff_freq\n must be a scalar. For a band-pass or band-reject filter, it must be\n a length 2 list.\n stop_band_attenuation : float, default=120\n The stop band attenuation in dB\n transition_bw : float, list or None, default=None\n The transition band-width in Hz.\n If None, sox's default of 5% of the total bandwith is used.\n If a float, the given transition bandwith is used for both the\n upper and lower bands (if applicable).\n If a list, the first argument is used for the lower band and the\n second for the upper band.\n phase_response : float or None\n The filter's phase response between 0 (minimum) and 100 (maximum).\n If None, sox's default phase repsonse is used.\n\n See Also\n --------\n band, bandpass, bandreject, highpass, lowpass\n '''\n filter_types = ['high', 'low', 'pass', 'reject']\n if filter_type not in filter_types:\n raise ValueError(\n \"filter_type must be one of {}\".format(', '.join(filter_types))\n )\n\n if not (is_number(cutoff_freq) or isinstance(cutoff_freq, list)):\n raise ValueError(\"cutoff_freq must be a number or a list\")\n\n if filter_type in ['high', 'low'] and isinstance(cutoff_freq, list):\n raise ValueError(\n \"For filter types 'high' and 'low', \"\n \"cutoff_freq must be a float, not a list\"\n )\n\n if filter_type in ['pass', 'reject'] and is_number(cutoff_freq):\n raise ValueError(\n \"For filter types 'pass' and 'reject', \"\n \"cutoff_freq must be a list, not a float\"\n )\n\n if is_number(cutoff_freq) and cutoff_freq <= 0:\n raise ValueError(\"cutoff_freq must be a postive number\")\n\n if isinstance(cutoff_freq, list):\n if len(cutoff_freq) != 2:\n raise ValueError(\n \"If cutoff_freq is a list it may only have 2 elements.\"\n )\n\n if any([not is_number(f) or f <= 0 for f in cutoff_freq]):\n raise ValueError(\n \"elements of cutoff_freq must be positive numbers\"\n )\n\n cutoff_freq = sorted(cutoff_freq)\n\n if not is_number(stop_band_attenuation) or stop_band_attenuation < 0:\n raise ValueError(\"stop_band_attenuation must be a positive number\")\n\n if not (is_number(transition_bw) or\n isinstance(transition_bw, list) or transition_bw is None):\n raise ValueError(\"transition_bw must be a number, a list or None.\")\n\n if filter_type in ['high', 'low'] and isinstance(transition_bw, list):\n raise ValueError(\n \"For filter types 'high' and 'low', \"\n \"transition_bw must be a float, not a list\"\n )\n\n if is_number(transition_bw) and transition_bw <= 0:\n raise ValueError(\"transition_bw must be a postive number\")\n\n if isinstance(transition_bw, list):\n if any([not is_number(f) or f <= 0 for f in transition_bw]):\n raise ValueError(\n \"elements of transition_bw must be positive numbers\"\n )\n if len(transition_bw) != 2:\n raise ValueError(\n \"If transition_bw is a list it may only have 2 elements.\"\n )\n\n if phase_response is not None and not is_number(phase_response):\n raise ValueError(\"phase_response must be a number or None.\")\n\n if (is_number(phase_response) and\n (phase_response < 0 or phase_response > 100)):\n raise ValueError(\"phase response must be between 0 and 100\")\n\n effect_args = ['sinc']\n effect_args.extend(['-a', '{:f}'.format(stop_band_attenuation)])\n\n if phase_response is not None:\n effect_args.extend(['-p', '{:f}'.format(phase_response)])\n\n if filter_type == 'high':\n if transition_bw is not None:\n effect_args.extend(['-t', '{:f}'.format(transition_bw)])\n effect_args.append('{:f}'.format(cutoff_freq))\n elif filter_type == 'low':\n effect_args.append('-{:f}'.format(cutoff_freq))\n if transition_bw is not None:\n effect_args.extend(['-t', '{:f}'.format(transition_bw)])\n else:\n if is_number(transition_bw):\n effect_args.extend(['-t', '{:f}'.format(transition_bw)])\n elif isinstance(transition_bw, list):\n effect_args.extend(['-t', '{:f}'.format(transition_bw[0])])\n\n if filter_type == 'pass':\n effect_args.append(\n '{:f}-{:f}'.format(cutoff_freq[0], cutoff_freq[1])\n )\n elif filter_type == 'reject':\n effect_args.append(\n '{:f}-{:f}'.format(cutoff_freq[1], cutoff_freq[0])\n )\n\n if isinstance(transition_bw, list):\n effect_args.extend(['-t', '{:f}'.format(transition_bw[1])])\n\n self.effects.extend(effect_args)\n self.effects_log.append('sinc')\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef speed(self, factor):\n '''Adjust the audio speed (pitch and tempo together).\n\n Technically, the speed effect only changes the sample rate information,\n leaving the samples themselves untouched. The rate effect is invoked\n automatically to resample to the output sample rate, using its default\n quality/speed. For higher quality or higher speed resampling, in\n addition to the speed effect, specify the rate effect with the desired\n quality option.\n\n Parameters\n ----------\n factor : float\n The ratio of the new speed to the old speed.\n For ex. 1.1 speeds up the audio by 10%; 0.9 slows it down by 10%.\n Note - this argument is the inverse of what is passed to the sox\n stretch effect for consistency with speed.\n\n See Also\n --------\n rate, tempo, pitch\n '''\n if not is_number(factor) or factor <= 0:\n raise ValueError(\"factor must be a positive number\")\n\n if factor < 0.5 or factor > 2:\n logger.warning(\n \"Using an extreme factor. Quality of results will be poor\"\n )\n\n effect_args = ['speed', '{:f}'.format(factor)]\n\n self.effects.extend(effect_args)\n self.effects_log.append('speed')\n\n return self", "response": "Adjust the audio speed."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef stat(self, input_filepath, scale=None, rms=False):\n '''Display time and frequency domain statistical information about the\n audio. Audio is passed unmodified through the SoX processing chain.\n\n Unlike other Transformer methods, this does not modify the transformer\n effects chain. Instead it computes statistics on the output file that\n would be created if the build command were invoked.\n\n Note: The file is downmixed to mono prior to computation.\n\n Parameters\n ----------\n input_filepath : str\n Path to input file to compute stats on.\n scale : float or None, default=None\n If not None, scales the input by the given scale factor.\n rms : bool, default=False\n If True, scales all values by the average rms amplitude.\n\n Returns\n -------\n stat_dict : dict\n Dictionary of statistics.\n\n See Also\n --------\n stats, power_spectrum, sox.file_info\n '''\n effect_args = ['channels', '1', 'stat']\n if scale is not None:\n if not is_number(scale) or scale <= 0:\n raise ValueError(\"scale must be a positive number.\")\n effect_args.extend(['-s', '{:f}'.format(scale)])\n\n if rms:\n effect_args.append('-rms')\n\n _, _, stat_output = self.build(\n input_filepath, None, extra_args=effect_args, return_output=True\n )\n\n stat_dict = {}\n lines = stat_output.split('\\n')\n for line in lines:\n split_line = line.split()\n if len(split_line) == 0:\n continue\n value = split_line[-1]\n key = ' '.join(split_line[:-1])\n stat_dict[key.strip(':')] = value\n\n return stat_dict", "response": "Display time and frequency domain statistical information about the given audio file."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef power_spectrum(self, input_filepath):\n '''Calculates the power spectrum (4096 point DFT). This method\n internally invokes the stat command with the -freq option.\n\n Note: The file is downmixed to mono prior to computation.\n\n Parameters\n ----------\n input_filepath : str\n Path to input file to compute stats on.\n\n Returns\n -------\n power_spectrum : list\n List of frequency (Hz), amplitude pairs.\n\n See Also\n --------\n stat, stats, sox.file_info\n '''\n effect_args = ['channels', '1', 'stat', '-freq']\n\n _, _, stat_output = self.build(\n input_filepath, None, extra_args=effect_args, return_output=True\n )\n\n power_spectrum = []\n lines = stat_output.split('\\n')\n for line in lines:\n split_line = line.split()\n if len(split_line) != 2:\n continue\n\n freq, amp = split_line\n power_spectrum.append([float(freq), float(amp)])\n\n return power_spectrum", "response": "Calculates the power spectrum of the specified file."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ndisplays time domain statistical information about the audio file that is passed unmodified through the SoX processing chain.", "response": "def stats(self, input_filepath):\n '''Display time domain statistical information about the audio\n channels. Audio is passed unmodified through the SoX processing chain.\n Statistics are calculated and displayed for each audio channel\n\n Unlike other Transformer methods, this does not modify the transformer\n effects chain. Instead it computes statistics on the output file that\n would be created if the build command were invoked.\n\n Note: The file is downmixed to mono prior to computation.\n\n Parameters\n ----------\n input_filepath : str\n Path to input file to compute stats on.\n\n Returns\n -------\n stats_dict : dict\n List of frequency (Hz), amplitude pairs.\n\n See Also\n --------\n stat, sox.file_info\n '''\n effect_args = ['channels', '1', 'stats']\n\n _, _, stats_output = self.build(\n input_filepath, None, extra_args=effect_args, return_output=True\n )\n\n stats_dict = {}\n lines = stats_output.split('\\n')\n for line in lines:\n split_line = line.split()\n if len(split_line) == 0:\n continue\n value = split_line[-1]\n key = ' '.join(split_line[:-1])\n stats_dict[key] = value\n\n return stats_dict"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef stretch(self, factor, window=20):\n '''Change the audio duration (but not its pitch).\n **Unless factor is close to 1, use the tempo effect instead.**\n\n This effect is broadly equivalent to the tempo effect with search set\n to zero, so in general, its results are comparatively poor; it is\n retained as it can sometimes out-perform tempo for small factors.\n\n Parameters\n ----------\n factor : float\n The ratio of the new tempo to the old tempo.\n For ex. 1.1 speeds up the tempo by 10%; 0.9 slows it down by 10%.\n Note - this argument is the inverse of what is passed to the sox\n stretch effect for consistency with tempo.\n window : float, default=20\n Window size in miliseconds\n\n See Also\n --------\n tempo, speed, pitch\n\n '''\n if not is_number(factor) or factor <= 0:\n raise ValueError(\"factor must be a positive number\")\n\n if factor < 0.5 or factor > 2:\n logger.warning(\n \"Using an extreme time stretching factor. \"\n \"Quality of results will be poor\"\n )\n\n if abs(factor - 1.0) > 0.1:\n logger.warning(\n \"For this stretch factor, \"\n \"the tempo effect has better performance.\"\n )\n\n if not is_number(window) or window <= 0:\n raise ValueError(\n \"window must be a positive number.\"\n )\n\n effect_args = ['stretch', '{:f}'.format(factor), '{:f}'.format(window)]\n\n self.effects.extend(effect_args)\n self.effects_log.append('stretch')\n\n return self", "response": "Change the duration of the audio."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nswap stereo channels. If the input is not stereo, pairs of channels are swapped, and a possible odd last channel passed through. E.g., for seven channels, the output order will be 2, 1, 4, 3, 6, 5, 7. See Also ---------- remix", "response": "def swap(self):\n '''Swap stereo channels. If the input is not stereo, pairs of channels\n are swapped, and a possible odd last channel passed through.\n\n E.g., for seven channels, the output order will be 2, 1, 4, 3, 6, 5, 7.\n\n See Also\n ----------\n remix\n\n '''\n effect_args = ['swap']\n self.effects.extend(effect_args)\n self.effects_log.append('swap')\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef tempo(self, factor, audio_type=None, quick=False):\n '''Time stretch audio without changing pitch.\n\n This effect uses the WSOLA algorithm. The audio is chopped up into\n segments which are then shifted in the time domain and overlapped\n (cross-faded) at points where their waveforms are most similar as\n determined by measurement of least squares.\n\n Parameters\n ----------\n factor : float\n The ratio of new tempo to the old tempo.\n For ex. 1.1 speeds up the tempo by 10%; 0.9 slows it down by 10%.\n audio_type : str\n Type of audio, which optimizes algorithm parameters. One of:\n * m : Music,\n * s : Speech,\n * l : Linear (useful when factor is close to 1),\n quick : bool, default=False\n If True, this effect will run faster but with lower sound quality.\n\n See Also\n --------\n stretch, speed, pitch\n\n '''\n if not is_number(factor) or factor <= 0:\n raise ValueError(\"factor must be a positive number\")\n\n if factor < 0.5 or factor > 2:\n logger.warning(\n \"Using an extreme time stretching factor. \"\n \"Quality of results will be poor\"\n )\n\n if abs(factor - 1.0) <= 0.1:\n logger.warning(\n \"For this stretch factor, \"\n \"the stretch effect has better performance.\"\n )\n\n if audio_type not in [None, 'm', 's', 'l']:\n raise ValueError(\n \"audio_type must be one of None, 'm', 's', or 'l'.\"\n )\n\n if not isinstance(quick, bool):\n raise ValueError(\"quick must be a boolean.\")\n\n effect_args = ['tempo']\n\n if quick:\n effect_args.append('-q')\n\n if audio_type is not None:\n effect_args.append('-{}'.format(audio_type))\n\n effect_args.append('{:f}'.format(factor))\n\n self.effects.extend(effect_args)\n self.effects_log.append('tempo')\n\n return self", "response": "This effect uses the WSOLA algorithm to adjust the tempo of the audio."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nboost or cut the treble frequencies of the audio using two - pole shelving filter with a response similar to that of a standard hi - fi\u2019s tone - controls.", "response": "def treble(self, gain_db, frequency=3000.0, slope=0.5):\n '''Boost or cut the treble (lower) frequencies of the audio using a\n two-pole shelving filter with a response similar to that of a standard\n hi-fi\u2019s tone-controls. This is also known as shelving equalisation.\n\n The filters are described in detail in\n http://musicdsp.org/files/Audio-EQ-Cookbook.txt\n\n Parameters\n ----------\n gain_db : float\n The gain at the Nyquist frequency.\n For a large cut use -20, for a large boost use 20.\n frequency : float, default=100.0\n The filter's cutoff frequency in Hz.\n slope : float, default=0.5\n The steepness of the filter's shelf transition.\n For a gentle slope use 0.3, and use 1.0 for a steep slope.\n\n See Also\n --------\n bass, equalizer\n\n '''\n if not is_number(gain_db):\n raise ValueError(\"gain_db must be a number\")\n\n if not is_number(frequency) or frequency <= 0:\n raise ValueError(\"frequency must be a positive number.\")\n\n if not is_number(slope) or slope <= 0 or slope > 1.0:\n raise ValueError(\"width_q must be a positive number.\")\n\n effect_args = [\n 'treble', '{:f}'.format(gain_db), '{:f}'.format(frequency),\n '{:f}s'.format(slope)\n ]\n\n self.effects.extend(effect_args)\n self.effects_log.append('treble')\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef tremolo(self, speed=6.0, depth=40.0):\n '''Apply a tremolo (low frequency amplitude modulation) effect to the\n audio. The tremolo frequency in Hz is giv en by speed, and the depth\n as a percentage by depth (default 40).\n\n Parameters\n ----------\n speed : float\n Tremolo speed in Hz.\n depth : float\n Tremolo depth as a percentage of the total amplitude.\n\n See Also\n --------\n flanger\n\n Examples\n --------\n >>> tfm = sox.Transformer()\n\n For a growl-type effect\n\n >>> tfm.tremolo(speed=100.0)\n '''\n if not is_number(speed) or speed <= 0:\n raise ValueError(\"speed must be a positive number.\")\n if not is_number(depth) or depth <= 0 or depth > 100:\n raise ValueError(\"depth must be a positive number less than 100.\")\n\n effect_args = [\n 'tremolo',\n '{:f}'.format(speed),\n '{:f}'.format(depth)\n ]\n\n self.effects.extend(effect_args)\n self.effects_log.append('tremolo')\n\n return self", "response": "Apply a tremolo effect to the entry."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nexcerpting a clip from an audio file given the start and end timestamps of the clip.", "response": "def trim(self, start_time, end_time=None):\n '''Excerpt a clip from an audio file, given the start timestamp and end timestamp of the clip within the file, expressed in seconds. If the end timestamp is set to `None` or left unspecified, it defaults to the duration of the audio file.\n\n Parameters\n ----------\n start_time : float\n Start time of the clip (seconds)\n end_time : float or None, default=None\n End time of the clip (seconds)\n\n '''\n if not is_number(start_time) or start_time < 0:\n raise ValueError(\"start_time must be a positive number.\")\n\n effect_args = [\n 'trim',\n '{:f}'.format(start_time)\n ]\n\n if end_time is not None:\n if not is_number(end_time) or end_time < 0:\n raise ValueError(\"end_time must be a positive number.\")\n if start_time >= end_time:\n raise ValueError(\"start_time must be smaller than end_time.\")\n\n effect_args.append('{:f}'.format(end_time - start_time))\n\n self.effects.extend(effect_args)\n self.effects_log.append('trim')\n\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef vad(self, location=1, normalize=True, activity_threshold=7.0,\n min_activity_duration=0.25, initial_search_buffer=1.0,\n max_gap=0.25, initial_pad=0.0):\n '''Voice Activity Detector. Attempts to trim silence and quiet\n background sounds from the ends of recordings of speech. The algorithm\n currently uses a simple cepstral power measurement to detect voice, so\n may be fooled by other things, especially music.\n\n The effect can trim only from the front of the audio, so in order to\n trim from the back, the reverse effect must also be used.\n\n Parameters\n ----------\n location : 1 or -1, default=1\n If 1, trims silence from the beginning\n If -1, trims silence from the end\n normalize : bool, default=True\n If true, normalizes audio before processing.\n activity_threshold : float, default=7.0\n The measurement level used to trigger activity detection. This may\n need to be cahnged depending on the noise level, signal level, and\n other characteristics of the input audio.\n min_activity_duration : float, default=0.25\n The time constant (in seconds) used to help ignore short bursts of\n sound.\n initial_search_buffer : float, default=1.0\n The amount of audio (in seconds) to search for quieter/shorter\n bursts of audio to include prior to the detected trigger point.\n max_gap : float, default=0.25\n The allowed gap (in seconds) between quiteter/shorter bursts of\n audio to include prior to the detected trigger point\n initial_pad : float, default=0.0\n The amount of audio (in seconds) to preserve before the trigger\n point and any found quieter/shorter bursts.\n\n See Also\n --------\n silence\n\n Examples\n --------\n >>> tfm = sox.Transformer()\n\n Remove silence from the beginning of speech\n\n >>> tfm.vad(initial_pad=0.3)\n\n Remove silence from the end of speech\n\n >>> tfm.vad(location=-1, initial_pad=0.2)\n\n '''\n if location not in [-1, 1]:\n raise ValueError(\"location must be -1 or 1.\")\n if not isinstance(normalize, bool):\n raise ValueError(\"normalize muse be a boolean.\")\n if not is_number(activity_threshold):\n raise ValueError(\"activity_threshold must be a number.\")\n if not is_number(min_activity_duration) or min_activity_duration < 0:\n raise ValueError(\"min_activity_duration must be a positive number\")\n if not is_number(initial_search_buffer) or initial_search_buffer < 0:\n raise ValueError(\"initial_search_buffer must be a positive number\")\n if not is_number(max_gap) or max_gap < 0:\n raise ValueError(\"max_gap must be a positive number.\")\n if not is_number(initial_pad) or initial_pad < 0:\n raise ValueError(\"initial_pad must be a positive number.\")\n\n effect_args = []\n\n if normalize:\n effect_args.append('norm')\n\n if location == -1:\n effect_args.append('reverse')\n\n effect_args.extend([\n 'vad',\n '-t', '{:f}'.format(activity_threshold),\n '-T', '{:f}'.format(min_activity_duration),\n '-s', '{:f}'.format(initial_search_buffer),\n '-g', '{:f}'.format(max_gap),\n '-p', '{:f}'.format(initial_pad)\n ])\n\n if location == -1:\n effect_args.append('reverse')\n\n self.effects.extend(effect_args)\n self.effects_log.append('vad')\n\n return self", "response": "This method is used to detect voice activity in the audio file."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef vol(self, gain, gain_type='amplitude', limiter_gain=None):\n '''Apply an amplification or an attenuation to the audio signal.\n\n Parameters\n ----------\n gain : float\n Interpreted according to the given `gain_type`.\n If `gain_type' = 'amplitude', `gain' is a positive amplitude ratio.\n If `gain_type' = 'power', `gain' is a power (voltage squared).\n If `gain_type' = 'db', `gain' is in decibels.\n gain_type : string, default='amplitude'\n Type of gain. One of:\n - 'amplitude'\n - 'power'\n - 'db'\n limiter_gain : float or None, default=None\n If specified, a limiter is invoked on peaks greater than\n `limiter_gain' to prevent clipping.\n `limiter_gain` should be a positive value much less than 1.\n\n See Also\n --------\n gain, compand\n\n '''\n if not is_number(gain):\n raise ValueError('gain must be a number.')\n if limiter_gain is not None:\n if (not is_number(limiter_gain) or\n limiter_gain <= 0 or limiter_gain >= 1):\n raise ValueError(\n 'limiter gain must be a positive number less than 1'\n )\n if gain_type in ['amplitude', 'power'] and gain < 0:\n raise ValueError(\n \"If gain_type = amplitude or power, gain must be positive.\"\n )\n\n effect_args = ['vol']\n\n effect_args.append('{:f}'.format(gain))\n\n if gain_type == 'amplitude':\n effect_args.append('amplitude')\n elif gain_type == 'power':\n effect_args.append('power')\n elif gain_type == 'db':\n effect_args.append('dB')\n else:\n raise ValueError('gain_type must be one of amplitude power or db')\n\n if limiter_gain is not None:\n if gain_type in ['amplitude', 'power'] and gain > 1:\n effect_args.append('{:f}'.format(limiter_gain))\n elif gain_type == 'db' and gain > 0:\n effect_args.append('{:f}'.format(limiter_gain))\n\n self.effects.extend(effect_args)\n self.effects_log.append('vol')\n\n return self", "response": "Applies an amplification or attenuation to the audio signal."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef join(self, room):\n self.socket.rooms.add(self._get_room_name(room))", "response": "Lets a user join a room on a specific Namespace."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef leave(self, room):\n self.socket.rooms.remove(self._get_room_name(room))", "response": "Lets a user leave a room on a specific Namespace."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _save_ack_callback(self, msgid, callback):\n if msgid in self.ack_callbacks:\n return False\n self.ack_callbacks[msgid] = callback", "response": "Save the callback for the given message ID."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngetting the callback for a given msgid if it exists otherwise return None", "response": "def _pop_ack_callback(self, msgid):\n \"\"\"Fetch the callback for a given msgid, if it exists, otherwise,\n return None\"\"\"\n if msgid not in self.ack_callbacks:\n return None\n return self.ack_callbacks.pop(msgid)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nkilling the current instance of the current object.", "response": "def kill(self, detach=False):\n \"\"\"This function must/will be called when a socket is to be completely\n shut down, closed by connection timeout, connection error or explicit\n disconnection from the client.\n\n It will call all of the Namespace's\n :meth:`~socketio.namespace.BaseNamespace.disconnect` methods\n so that you can shut-down things properly.\n\n \"\"\"\n # Clear out the callbacks\n self.ack_callbacks = {}\n if self.connected:\n self.state = self.STATE_DISCONNECTING\n self.server_queue.put_nowait(None)\n self.client_queue.put_nowait(None)\n if len(self.active_ns) > 0:\n log.debug(\"Calling disconnect() on %s\" % self)\n self.disconnect()\n\n if detach:\n self.detach()\n\n gevent.killall(self.jobs)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ndetaches this socket from the server.", "response": "def detach(self):\n \"\"\"Detach this socket from the server. This should be done in\n conjunction with kill(), once all the jobs are dead, detach the\n socket for garbage collection.\"\"\"\n\n log.debug(\"Removing %s from server sockets\" % self)\n if self.sessid in self.server.sockets:\n self.server.sockets.pop(self.sessid)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting multiple messages in case we re going through the various XHR - polling methods on which we can pack more than one message.", "response": "def get_multiple_client_msgs(self, **kwargs):\n \"\"\"Get multiple messages, in case we're going through the various\n XHR-polling methods, on which we can pack more than one message if the\n rate is high, and encode the payload for the HTTP channel.\"\"\"\n client_queue = self.client_queue\n msgs = [client_queue.get(**kwargs)]\n while client_queue.qsize():\n msgs.append(client_queue.get())\n return msgs"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nsending an error to the user using the custom error handler.", "response": "def error(self, error_name, error_message, endpoint=None, msg_id=None,\n quiet=False):\n \"\"\"Send an error to the user, using the custom or default\n ErrorHandler configured on the [TODO: Revise this] Socket/Handler\n object.\n\n :param error_name: is a simple string, for easy association on\n the client side\n\n :param error_message: is a human readable message, the user\n will eventually see\n\n :param endpoint: set this if you have a message specific to an\n end point\n\n :param msg_id: set this if your error is relative to a\n specific message\n\n :param quiet: way to make the error handler quiet. Specific to\n the handler. The default handler will only log,\n with quiet.\n \"\"\"\n handler = self.error_handler\n return handler(\n self, error_name, error_message, endpoint, msg_id, quiet)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ndisconnect all the active Namespaces and sends a disconnect packet for each of them.", "response": "def disconnect(self, silent=False):\n \"\"\"Calling this method will call the\n :meth:`~socketio.namespace.BaseNamespace.disconnect` method on\n all the active Namespaces that were open, killing all their\n jobs and sending 'disconnect' packets for each of them.\n\n Normally, the Global namespace (endpoint = '') has special meaning,\n as it represents the whole connection,\n\n :param silent: when True, pass on the ``silent`` flag to the Namespace\n :meth:`~socketio.namespace.BaseNamespace.disconnect`\n calls.\n \"\"\"\n for ns_name, ns in list(six.iteritems(self.active_ns)):\n ns.recv_disconnect()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef send_packet(self, pkt):\n self.put_client_msg(packet.encode(pkt, self.json_dumps))", "response": "Send a packet on the wire."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nspawns a new sub - socket.", "response": "def spawn(self, fn, *args, **kwargs):\n \"\"\"Spawn a new Greenlet, attached to this Socket instance.\n\n It will be monitored by the \"watcher\" method\n \"\"\"\n\n log.debug(\"Spawning sub-Socket Greenlet: %s\" % fn.__name__)\n job = gevent.spawn(fn, *args, **kwargs)\n self.jobs.append(job)\n return job"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _receiver_loop(self):\n\n while True:\n rawdata = self.get_server_msg()\n\n if not rawdata:\n continue # or close the connection ?\n try:\n pkt = packet.decode(rawdata, self.json_loads)\n except (ValueError, KeyError, Exception) as e:\n self.error('invalid_packet',\n \"There was a decoding error when dealing with packet \"\n \"with event: %s... (%s)\" % (rawdata[:20], e))\n continue\n\n if pkt['type'] == 'heartbeat':\n # This is already dealth with in put_server_msg() when\n # any incoming raw data arrives.\n continue\n\n if pkt['type'] == 'disconnect' and pkt['endpoint'] == '':\n # On global namespace, we kill everything.\n self.kill(detach=True)\n continue\n\n endpoint = pkt['endpoint']\n\n if endpoint not in self.namespaces:\n self.error(\"no_such_namespace\",\n \"The endpoint you tried to connect to \"\n \"doesn't exist: %s\" % endpoint, endpoint=endpoint)\n continue\n elif endpoint in self.active_ns:\n pkt_ns = self.active_ns[endpoint]\n else:\n new_ns_class = self.namespaces[endpoint]\n pkt_ns = new_ns_class(self.environ, endpoint,\n request=self.request)\n # This calls initialize() on all the classes and mixins, etc..\n # in the order of the MRO\n for cls in type(pkt_ns).__mro__:\n if hasattr(cls, 'initialize'):\n cls.initialize(pkt_ns) # use this instead of __init__,\n # for less confusion\n\n self.active_ns[endpoint] = pkt_ns\n\n retval = pkt_ns.process_packet(pkt)\n\n # Has the client requested an 'ack' with the reply parameters ?\n if pkt.get('ack') == \"data\" and pkt.get('id'):\n if type(retval) is tuple:\n args = list(retval)\n else:\n args = [retval]\n returning_ack = dict(type='ack', ackId=pkt['id'],\n args=args,\n endpoint=pkt.get('endpoint', ''))\n self.send_packet(returning_ack)\n\n # Now, are we still connected ?\n if not self.connected:\n self.kill(detach=True) # ?? what,s the best clean-up\n # when its not a\n # user-initiated disconnect\n return", "response": "This is the main loop that takes messages from the queue and decodes them and dispatches them."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nspawn the receiver loop.", "response": "def _spawn_receiver_loop(self):\n \"\"\"Spawns the reader loop. This is called internall by\n socketio_manage().\n \"\"\"\n job = gevent.spawn(self._receiver_loop)\n self.jobs.append(job)\n return job"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nwatching out if we ve been disconnected and kill all the jobs.", "response": "def _watcher(self):\n \"\"\"Watch out if we've been disconnected, in that case, kill\n all the jobs.\n\n \"\"\"\n while True:\n gevent.sleep(1.0)\n if not self.connected:\n for ns_name, ns in list(six.iteritems(self.active_ns)):\n ns.recv_disconnect()\n # Killing Socket-level jobs\n gevent.killall(self.jobs)\n break"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _heartbeat(self):\n interval = self.config['heartbeat_interval']\n while self.connected:\n gevent.sleep(interval)\n # TODO: this process could use a timeout object like the disconnect\n # timeout thing, and ONLY send packets when none are sent!\n # We would do that by calling timeout.set() for a \"sending\"\n # timeout. If we're sending 100 messages a second, there is\n # no need to push some heartbeats in there also.\n self.put_client_msg(\"2::\")", "response": "Start the heartbeat Greenlet to check connection health."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef encode(data, json_dumps=default_json_dumps):\n payload = ''\n msg = str(MSG_TYPES[data['type']])\n\n if msg in ['0', '1']:\n # '1::' [path] [query]\n msg += '::' + data['endpoint']\n if 'qs' in data and data['qs'] != '':\n msg += ':' + data['qs']\n\n elif msg == '2':\n # heartbeat\n msg += '::'\n\n elif msg in ['3', '4', '5']:\n # '3:' [id ('+')] ':' [endpoint] ':' [data]\n # '4:' [id ('+')] ':' [endpoint] ':' [json]\n # '5:' [id ('+')] ':' [endpoint] ':' [json encoded event]\n # The message id is an incremental integer, required for ACKs.\n # If the message id is followed by a +, the ACK is not handled by\n # socket.io, but by the user instead.\n if msg == '3':\n payload = data['data']\n if msg == '4':\n payload = json_dumps(data['data'])\n if msg == '5':\n d = {}\n d['name'] = data['name']\n if 'args' in data and data['args'] != []:\n d['args'] = data['args']\n payload = json_dumps(d)\n if 'id' in data:\n msg += ':' + str(data['id'])\n if data['ack'] == 'data':\n msg += '+'\n msg += ':'\n else:\n msg += '::'\n if 'endpoint' not in data:\n data['endpoint'] = ''\n if payload != '':\n msg += data['endpoint'] + ':' + payload\n else:\n msg += data['endpoint']\n\n elif msg == '6':\n # '6:::' [id] '+' [data]\n msg += '::' + data.get('endpoint', '') + ':' + str(data['ackId'])\n if 'args' in data and data['args'] != []:\n msg += '+' + json_dumps(data['args'])\n\n elif msg == '7':\n # '7::' [endpoint] ':' [reason] '+' [advice]\n msg += ':::'\n if 'reason' in data and data['reason'] != '':\n msg += str(ERROR_REASONS[data['reason']])\n if 'advice' in data and data['advice'] != '':\n msg += '+' + str(ERROR_ADVICES[data['advice']])\n msg += data['endpoint']\n\n # NoOp, used to close a poll after the polling duration time\n elif msg == '8':\n msg += '::'\n\n return msg", "response": "Encode an attribute dict into a byte string."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef decode(rawstr, json_loads=default_json_loads):\n decoded_msg = {}\n try:\n # Handle decoding in Python<3.\n rawstr = rawstr.decode('utf-8')\n except AttributeError:\n pass\n split_data = rawstr.split(\":\", 3)\n msg_type = split_data[0]\n msg_id = split_data[1]\n endpoint = split_data[2]\n\n data = ''\n\n if msg_id != '':\n if \"+\" in msg_id:\n msg_id = msg_id.split('+')[0]\n decoded_msg['id'] = int(msg_id)\n decoded_msg['ack'] = 'data'\n else:\n decoded_msg['id'] = int(msg_id)\n decoded_msg['ack'] = True\n\n # common to every message\n msg_type_id = int(msg_type)\n if msg_type_id in MSG_VALUES:\n decoded_msg['type'] = MSG_VALUES[int(msg_type)]\n else:\n raise Exception(\"Unknown message type: %s\" % msg_type)\n\n decoded_msg['endpoint'] = endpoint\n\n if len(split_data) > 3:\n data = split_data[3]\n\n if msg_type == \"0\": # disconnect\n pass\n\n elif msg_type == \"1\": # connect\n decoded_msg['qs'] = data\n\n elif msg_type == \"2\": # heartbeat\n pass\n\n elif msg_type == \"3\": # message\n decoded_msg['data'] = data\n\n elif msg_type == \"4\": # json msg\n decoded_msg['data'] = json_loads(data)\n\n elif msg_type == \"5\": # event\n try:\n data = json_loads(data)\n except ValueError:\n print(\"Invalid JSON event message\", data)\n decoded_msg['args'] = []\n else:\n decoded_msg['name'] = data.pop('name')\n if 'args' in data:\n decoded_msg['args'] = data['args']\n else:\n decoded_msg['args'] = []\n\n elif msg_type == \"6\": # ack\n if '+' in data:\n ackId, data = data.split('+')\n decoded_msg['ackId'] = int(ackId)\n decoded_msg['args'] = json_loads(data)\n else:\n decoded_msg['ackId'] = int(data)\n decoded_msg['args'] = []\n\n elif msg_type == \"7\": # error\n if '+' in data:\n reason, advice = data.split('+')\n decoded_msg['reason'] = REASONS_VALUES[int(reason)]\n decoded_msg['advice'] = ADVICES_VALUES[int(advice)]\n else:\n decoded_msg['advice'] = ''\n if data != '':\n decoded_msg['reason'] = REASONS_VALUES[int(data)]\n else:\n decoded_msg['reason'] = ''\n\n elif msg_type == \"8\": # noop\n pass\n\n return decoded_msg", "response": "Decode a rawstr packet arriving from the socket into a dict."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef add_acl_method(self, method_name):\n\n if isinstance(self.allowed_methods, set):\n self.allowed_methods.add(method_name)\n else:\n self.allowed_methods = set([method_name])", "response": "Add a method to the list of allowed methods"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef del_acl_method(self, method_name):\n if self.allowed_methods is None:\n raise ValueError(\n \"Trying to delete an ACL method, but none were\"\n + \" defined yet! Or: No ACL restrictions yet, why would you\"\n + \" delete one?\"\n )\n\n self.allowed_methods.remove(method_name)", "response": "Delete an ACL method from the ACL system."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef process_packet(self, packet):\n packet_type = packet['type']\n\n if packet_type == 'event':\n return self.process_event(packet)\n elif packet_type == 'message':\n return self.call_method_with_acl('recv_message', packet,\n packet['data'])\n elif packet_type == 'json':\n return self.call_method_with_acl('recv_json', packet,\n packet['data'])\n elif packet_type == 'connect':\n self.socket.send_packet(packet)\n return self.call_method_with_acl('recv_connect', packet)\n elif packet_type == 'error':\n return self.call_method_with_acl('recv_error', packet)\n elif packet_type == 'ack':\n callback = self.socket._pop_ack_callback(packet['ackId'])\n if not callback:\n print(\"ERROR: No such callback for ackId %s\" % packet['ackId'])\n return\n return callback(*(packet['args']))\n elif packet_type == 'disconnect':\n # Force a disconnect on the namespace.\n return self.call_method_with_acl('recv_disconnect', packet)\n else:\n print(\"Unprocessed packet\", packet)", "response": "This method processes a single packet and calls the appropriate method."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef call_method_with_acl(self, method_name, packet, *args):\n if not self.is_method_allowed(method_name):\n self.error('method_access_denied',\n 'You do not have access to method \"%s\"' % method_name)\n return\n\n return self.call_method(method_name, packet, *args)", "response": "Calls the method with ACLs"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef call_method(self, method_name, packet, *args):\n method = getattr(self, method_name, None)\n if method is None:\n self.error('no_such_method',\n 'The method \"%s\" was not found' % method_name)\n return\n\n specs = inspect.getargspec(method)\n func_args = specs.args\n if not len(func_args) or func_args[0] != 'self':\n self.error(\"invalid_method_args\",\n \"The server-side method is invalid, as it doesn't \"\n \"have 'self' as its first argument\")\n return\n\n # Check if we need to decorate to handle exceptions\n if hasattr(self, 'exception_handler_decorator'):\n method = self.exception_handler_decorator(method)\n\n if len(func_args) == 2 and func_args[1] == 'packet':\n return method(packet)\n else:\n return method(*args)", "response": "This function is used to implement the two behaviors on dispatched\n on_* and recv_* methods."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nusing this to send an error message to your application.", "response": "def error(self, error_name, error_message, msg_id=None, quiet=False):\n \"\"\"Use this to use the configured ``error_handler`` yield an\n error message to your application.\n\n :param error_name: is a short string, to associate messages to recovery\n methods\n :param error_message: is some human-readable text, describing the error\n :param msg_id: is used to associate with a request\n :param quiet: specific to error_handlers. The default doesn't send a\n message to the user, but shows a debug message on the\n developer console.\n \"\"\"\n self.socket.error(error_name, error_message, endpoint=self.ns_name,\n msg_id=msg_id, quiet=quiet)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef send(self, message, json=False, callback=None):\n pkt = dict(type=\"message\", data=message, endpoint=self.ns_name)\n if json:\n pkt['type'] = \"json\"\n\n if callback:\n # By passing ack=True, we use the old behavior of being returned\n # an 'ack' packet, automatically triggered by the client-side\n # with no user-code being run. The emit() version of the\n # callback is more useful I think :) So migrate your code.\n pkt['ack'] = True\n pkt['id'] = msgid = self.socket._get_next_msgid()\n self.socket._save_ack_callback(msgid, callback)\n\n self.socket.send_packet(pkt)", "response": "Use send to send a simple string message."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nsends an event to the remote end.", "response": "def emit(self, event, *args, **kwargs):\n \"\"\"Use this to send a structured event, with a name and arguments, to\n the client.\n\n By default, it uses this namespace's endpoint. You can send messages on\n other endpoints with something like:\n\n ``self.socket['/other_endpoint'].emit()``.\n\n However, it is possible that the ``'/other_endpoint'`` was not\n initialized yet, and that would yield a ``KeyError``.\n\n The only supported ``kwargs`` is ``callback``. All other parameters\n must be passed positionally.\n\n :param event: The name of the event to trigger on the other end.\n :param callback: Pass in the callback keyword argument to define a\n call-back that will be called when the client acks.\n\n This callback is slightly different from the one from\n ``send()``, as this callback will receive parameters\n from the explicit call of the ``ack()`` function\n passed to the listener on the client side.\n\n The remote listener will need to explicitly ack (by\n calling its last argument, a function which is\n usually called 'ack') with some parameters indicating\n success or error. The 'ack' packet coming back here\n will then trigger the callback function with the\n returned values.\n :type callback: callable\n \"\"\"\n callback = kwargs.pop('callback', None)\n\n if kwargs:\n raise ValueError(\n \"emit() only supports positional argument, to stay \"\n \"compatible with the Socket.IO protocol. You can \"\n \"however pass in a dictionary as the first argument\")\n pkt = dict(type=\"event\", name=event, args=args,\n endpoint=self.ns_name)\n\n if callback:\n # By passing 'data', we indicate that we *want* an explicit ack\n # by the client code, not an automatic as with send().\n pkt['ack'] = 'data'\n pkt['id'] = msgid = self.socket._get_next_msgid()\n self.socket._save_ack_callback(msgid, callback)\n\n self.socket.send_packet(pkt)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef spawn(self, fn, *args, **kwargs):\n # self.log.debug(\"Spawning sub-Namespace Greenlet: %s\" % fn.__name__)\n if hasattr(self, 'exception_handler_decorator'):\n fn = self.exception_handler_decorator(fn)\n new = gevent.spawn(fn, *args, **kwargs)\n self.jobs.append(new)\n return new", "response": "Spawn a new process attached to this namespace."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nsending a disconnect packet to the server and remove the local jobs from the Socket.", "response": "def disconnect(self, silent=False):\n \"\"\"Send a 'disconnect' packet, so that the user knows it has been\n disconnected (booted actually). This will trigger an onDisconnect()\n call on the client side.\n\n Over here, we will kill all ``spawn``ed processes and remove the\n namespace from the Socket object.\n\n :param silent: do not actually send the packet (if they asked for a\n disconnect for example), but just kill all jobs spawned\n by this Namespace, and remove it from the Socket.\n \"\"\"\n if not silent:\n packet = {\"type\": \"disconnect\",\n \"endpoint\": self.ns_name}\n self.socket.send_packet(packet)\n # remove_namespace might throw GreenletExit so\n # kill_local_jobs must be in finally\n try:\n self.socket.remove_namespace(self.ns_name)\n finally:\n self.kill_local_jobs()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning an existing or new client Socket.", "response": "def get_socket(self, sessid=''):\n \"\"\"Return an existing or new client Socket.\"\"\"\n\n socket = self.sockets.get(sessid)\n\n if sessid and not socket:\n return None # you ask for a session that doesn't exist!\n if socket is None:\n socket = Socket(self, self.config)\n self.sockets[socket.sessid] = socket\n else:\n socket.incr_hits()\n\n return socket"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef create():\n name = request.form.get(\"name\")\n if name:\n room, created = get_or_create(ChatRoom, name=name)\n return redirect(url_for('room', slug=room.slug))\n return redirect(url_for('rooms'))", "response": "Handles the Create room form on the homepage and generates a new room."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef autodiscover():\n global LOADING_SOCKETIO\n if LOADING_SOCKETIO:\n return\n LOADING_SOCKETIO = True\n\n import imp\n from django.conf import settings\n\n for app in settings.INSTALLED_APPS:\n\n try:\n app_path = import_module(app).__path__\n except AttributeError:\n continue\n\n try:\n imp.find_module('sockets', app_path)\n except ImportError:\n continue\n\n import_module(\"%s.sockets\" % app)\n\n LOADING_SOCKETIO = False", "response": "Auto - discover INSTALLED_APPS sockets. py modules and fail silently when there is no socketio module."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nencoding a list of messages to be unicode.", "response": "def encode_payload(self, messages):\n \"\"\"Encode list of messages. Expects messages to be unicode.\n\n ``messages`` - List of raw messages to encode, if necessary\n\n \"\"\"\n if not messages or messages[0] is None:\n return ''\n\n if len(messages) == 1:\n return messages[0].encode('utf-8')\n\n payload = u''.join([(u'\\ufffd%d\\ufffd%s' % (len(p), p))\n for p in messages if p is not None])\n # FIXME: why is it so that we must filter None from here ? How\n # is it even possible that a None gets in there ?\n\n return payload.encode('utf-8')"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef broadcast_event(self, event, *args):\n pkt = dict(type=\"event\",\n name=event,\n args=args,\n endpoint=self.ns_name)\n\n for sessid, socket in six.iteritems(self.socket.server.sockets):\n socket.send_packet(pkt)", "response": "Broadcasts an event to all the sockets in this particular Namespace."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nadding a parent to this role and add itself to the parent s children set.", "response": "def add_parent(self, parent):\n \"\"\"Add a parent to this role,\n and add role itself to the parent's children set.\n you should override this function if neccessary.\n\n Example::\n\n logged_user = RoleMixin('logged_user')\n student = RoleMixin('student')\n student.add_parent(logged_user)\n\n :param parent: Parent role to add in.\n \"\"\"\n parent.children.add(self)\n self.parents.add(parent)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nadds allowing rules. :param role: Role of this rule. :param method: Method to allow in rule, include GET, POST, PUT etc. :param resource: Resource also view function. :param with_children: Allow role's children in rule as well if with_children is `True`", "response": "def allow(self, role, method, resource, with_children=True):\n \"\"\"Add allowing rules.\n\n :param role: Role of this rule.\n :param method: Method to allow in rule, include GET, POST, PUT etc.\n :param resource: Resource also view function.\n :param with_children: Allow role's children in rule as well\n if with_children is `True`\n \"\"\"\n if with_children:\n for r in role.get_children():\n permission = (r.get_name(), method, resource)\n if permission not in self._allowed:\n self._allowed.append(permission)\n if role == 'anonymous':\n permission = (role, method, resource)\n else:\n permission = (role.get_name(), method, resource)\n if permission not in self._allowed:\n self._allowed.append(permission)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef deny(self, role, method, resource, with_children=False):\n if with_children:\n for r in role.get_children():\n permission = (r.get_name(), method, resource)\n if permission not in self._denied:\n self._denied.append(permission)\n permission = (role.get_name(), method, resource)\n if permission not in self._denied:\n self._denied.append(permission)", "response": "Add denying rules.\n\n :param role: Role of this rule.\n :param method: Method to deny in rule, include GET, POST, PUT etc.\n :param resource: Resource also view function.\n :param with_children: Deny role's children in rule as well\n if with_children is `True`"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef exempt(self, resource):\n if resource not in self._exempt:\n self._exempt.append(resource)", "response": "Exempt a view function from being checked permission\n "}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef is_allowed(self, role, method, resource):\n return (role, method, resource) in self._allowed", "response": "Check whether role is allowed to access resource\n "}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef is_denied(self, role, method, resource):\n return (role, method, resource) in self._denied", "response": "Check wherther role is denied to access resource\n "}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef init_app(self, app):\n\n app.config.setdefault('RBAC_USE_WHITE', False)\n self.use_white = app.config['RBAC_USE_WHITE']\n\n if not hasattr(app, 'extensions'):\n app.extensions = {}\n app.extensions['rbac'] = _RBACState(self, app)\n\n self.acl.allow(anonymous, 'GET', 'static')\n app.before_first_request(self._setup_acl)\n\n app.before_request(self._authenticate)", "response": "Initialize application in Flask - RBAC."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef has_permission(self, method, endpoint, user=None):\n app = self.get_app()\n _user = user or self._user_loader()\n if not hasattr(_user, 'get_roles'):\n roles = [anonymous]\n else:\n roles = _user.get_roles()\n return self._check_permission(roles, method, endpoint)", "response": "Return True if the current user can access the resource."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nremoves all binary files in the adslib directory.", "response": "def remove_binaries():\r\n \"\"\"Remove all binary files in the adslib directory.\"\"\"\r\n patterns = (\r\n \"adslib/*.a\",\r\n \"adslib/*.o\",\r\n \"adslib/obj/*.o\",\r\n \"adslib/*.bin\",\r\n \"adslib/*.so\",\r\n )\r\n\r\n for f in functools.reduce(operator.iconcat, [glob.glob(p) for p in patterns]):\r\n os.remove(f)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef router_function(fn):\n # type: (Callable) -> Callable\n \"\"\"Raise a runtime error if on Win32 systems.\n\n Decorator.\n\n Decorator for functions that interact with the router for the Linux\n implementation of the ADS library.\n\n Unlike the Windows implementation which uses a separate router daemon,\n the Linux library manages AMS routing in-process. As such, routing must be\n configured programatically via. the provided API. These endpoints are\n invalid on Win32 systems, so an exception will be raised.\n\n \"\"\"\n\n @wraps(fn)\n def wrapper(*args, **kwargs):\n # type: (Any, Any) -> Callable\n if platform_is_windows(): # pragma: no cover, skipt Windows test\n raise RuntimeError(\n \"Router interface is not available on Win32 systems.\\n\"\n \"Configure AMS routes using the TwinCAT router service.\"\n )\n return fn(*args, **kwargs)\n\n return wrapper", "response": "Decorator for TwinCAT router functions."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef adsAddRoute(net_id, ip_address):\n # type: (SAmsNetId, str) -> None\n \"\"\"Establish a new route in the AMS Router.\n\n :param pyads.structs.SAmsNetId net_id: net id of routing endpoint\n :param str ip_address: ip address of the routing endpoint\n\n \"\"\"\n add_route = _adsDLL.AdsAddRoute\n add_route.restype = ctypes.c_long\n\n # Convert ip address to bytes (PY3) and get pointer.\n ip_address_p = ctypes.c_char_p(ip_address.encode(\"utf-8\"))\n\n error_code = add_route(net_id, ip_address_p)\n\n if error_code:\n raise ADSError(error_code)", "response": "Establish a new route in the AMS Router."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nconnects to the TwinCAT message router.", "response": "def adsPortOpenEx():\n # type: () -> int\n \"\"\"Connect to the TwinCAT message router.\n\n :rtype: int\n :return: port number\n\n \"\"\"\n port_open_ex = _adsDLL.AdsPortOpenEx\n port_open_ex.restype = ctypes.c_long\n port = port_open_ex()\n\n if port == 0:\n raise RuntimeError(\"Failed to open port on AMS router.\")\n\n return port"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncloses the connection to the TwinCAT message router.", "response": "def adsPortCloseEx(port):\n # type: (int) -> None\n \"\"\"Close the connection to the TwinCAT message router.\"\"\"\n port_close_ex = _adsDLL.AdsPortCloseEx\n port_close_ex.restype = ctypes.c_long\n error_code = port_close_ex(port)\n\n if error_code:\n raise ADSError(error_code)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef adsGetLocalAddressEx(port):\n # type: (int) -> AmsAddr\n \"\"\"Return the local AMS-address and the port number.\n\n :rtype: pyads.structs.AmsAddr\n :return: AMS-address\n\n \"\"\"\n get_local_address_ex = _adsDLL.AdsGetLocalAddressEx\n ams_address_struct = SAmsAddr()\n error_code = get_local_address_ex(port, ctypes.pointer(ams_address_struct))\n\n if error_code:\n raise ADSError(error_code)\n\n local_ams_address = AmsAddr()\n local_ams_address._ams_addr = ams_address_struct\n\n return local_ams_address", "response": "Returns the local AMS - address and the port number."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreading the current ADS-state and the machine-state. Read the current ADS-state and the machine-state from the ADS-server. :param pyads.structs.AmsAddr address: local or remote AmsAddr :rtype: (int, int) :return: ads_state, device_state", "response": "def adsSyncReadStateReqEx(port, address):\n # type: (int, AmsAddr) -> Tuple[int, int]\n \"\"\"Read the current ADS-state and the machine-state.\n\n Read the current ADS-state and the machine-state from the\n ADS-server.\n\n :param pyads.structs.AmsAddr address: local or remote AmsAddr\n :rtype: (int, int)\n :return: ads_state, device_state\n\n \"\"\"\n sync_read_state_request = _adsDLL.AdsSyncReadStateReqEx\n\n # C pointer to ams address struct\n ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n\n # Current ADS status and corresponding pointer\n ads_state = ctypes.c_int()\n ads_state_pointer = ctypes.pointer(ads_state)\n\n # Current device status and corresponding pointer\n device_state = ctypes.c_int()\n device_state_pointer = ctypes.pointer(device_state)\n\n error_code = sync_read_state_request(\n port, ams_address_pointer, ads_state_pointer, device_state_pointer\n )\n\n if error_code:\n raise ADSError(error_code)\n\n return (ads_state.value, device_state.value)"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreads the name and version number of the ADS - server.", "response": "def adsSyncReadDeviceInfoReqEx(port, address):\n # type: (int, AmsAddr) -> Tuple[str, AdsVersion]\n \"\"\"Read the name and the version number of the ADS-server.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param pyads.structs.AmsAddr address: local or remote AmsAddr\n :rtype: string, AdsVersion\n :return: device name, version\n\n \"\"\"\n sync_read_device_info_request = _adsDLL.AdsSyncReadDeviceInfoReqEx\n\n # Get pointer to the target AMS address\n ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n\n # Create buffer to be filled with device name, get pointer to said buffer\n device_name_buffer = ctypes.create_string_buffer(20)\n device_name_pointer = ctypes.pointer(device_name_buffer)\n\n # Create ADS Version struct and get pointer.\n ads_version = SAdsVersion()\n ads_version_pointer = ctypes.pointer(ads_version)\n\n error_code = sync_read_device_info_request(\n port, ams_address_pointer, device_name_pointer, ads_version_pointer\n )\n\n if error_code:\n raise ADSError(error_code)\n\n return (device_name_buffer.value.decode(), AdsVersion(ads_version))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nchanging the state of the ADS - server and the machine - state of the ADS - server.", "response": "def adsSyncWriteControlReqEx(\n port, address, ads_state, device_state, data, plc_data_type\n):\n # type: (int, AmsAddr, int, int, Any, Type) -> None\n \"\"\"Change the ADS state and the machine-state of the ADS-server.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n :param int ads_state: new ADS-state, according to ADSTATE constants\n :param int device_state: new machine-state\n :param data: additional data\n :param int plc_data_type: plc datatype, according to PLCTYPE constants\n\n \"\"\"\n sync_write_control_request = _adsDLL.AdsSyncWriteControlReqEx\n\n ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n ads_state_c = ctypes.c_ulong(ads_state)\n device_state_c = ctypes.c_ulong(device_state)\n\n if plc_data_type == PLCTYPE_STRING:\n data = ctypes.c_char_p(data.encode(\"utf-8\"))\n data_pointer = data\n data_length = len(data_pointer.value) + 1\n else:\n data = plc_data_type(data)\n data_pointer = ctypes.pointer(data)\n data_length = ctypes.sizeof(data)\n\n error_code = sync_write_control_request(\n port,\n ams_address_pointer,\n ads_state_c,\n device_state_c,\n data_length,\n data_pointer,\n )\n\n if error_code:\n raise ADSError(error_code)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nsending data synchronous to an AMS - device.", "response": "def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type):\n # type: (int, AmsAddr, int, int, Any, Type) -> None\n \"\"\"Send data synchronous to an ADS-device.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param pyads.structs.AmsAddr address: local or remote AmsAddr\n :param int indexGroup: PLC storage area, according to the INDEXGROUP\n constants\n :param int index_offset: PLC storage address\n :param value: value to write to the storage address of the PLC\n :param int plc_data_type: type of the data given to the PLC,\n according to PLCTYPE constants\n\n \"\"\"\n sync_write_request = _adsDLL.AdsSyncWriteReqEx\n\n ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n index_group_c = ctypes.c_ulong(index_group)\n index_offset_c = ctypes.c_ulong(index_offset)\n\n if plc_data_type == PLCTYPE_STRING:\n data = ctypes.c_char_p(value.encode(\"utf-8\"))\n data_pointer = data # type: Union[ctypes.c_char_p, ctypes.pointer]\n data_length = len(data_pointer.value) + 1 # type: ignore\n\n else:\n if type(plc_data_type).__name__ == \"PyCArrayType\":\n data = plc_data_type(*value)\n else:\n data = plc_data_type(value)\n\n data_pointer = ctypes.pointer(data)\n data_length = ctypes.sizeof(data)\n\n error_code = sync_write_request(\n port,\n ams_address_pointer,\n index_group_c,\n index_offset_c,\n data_length,\n data_pointer,\n )\n\n if error_code:\n raise ADSError(error_code)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreads and write data synchronous from/to an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :param int index_group: PLC storage area, according to the INDEXGROUP constants :param int index_offset: PLC storage address :param Type read_data_type: type of the data given to the PLC to respond to, according to PLCTYPE constants :param value: value to write to the storage address of the PLC :param Type write_data_type: type of the data given to the PLC, according to PLCTYPE constants :param bool return_ctypes: return ctypes instead of python types if True (default: False) :rtype: read_data_type :return: value: value read from PLC", "response": "def adsSyncReadWriteReqEx2(\n port,\n address,\n index_group,\n index_offset,\n read_data_type,\n value,\n write_data_type,\n return_ctypes=False,\n):\n # type: (int, AmsAddr, int, int, Type, Any, Type, bool) -> Any\n \"\"\"Read and write data synchronous from/to an ADS-device.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param pyads.structs.AmsAddr address: local or remote AmsAddr\n :param int index_group: PLC storage area, according to the INDEXGROUP\n constants\n :param int index_offset: PLC storage address\n :param Type read_data_type: type of the data given to the PLC to respond to,\n according to PLCTYPE constants\n :param value: value to write to the storage address of the PLC\n :param Type write_data_type: type of the data given to the PLC, according to\n PLCTYPE constants\n :param bool return_ctypes: return ctypes instead of python types if True\n (default: False)\n :rtype: read_data_type\n :return: value: value read from PLC\n\n \"\"\"\n sync_read_write_request = _adsDLL.AdsSyncReadWriteReqEx2\n\n ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n index_group_c = ctypes.c_ulong(index_group)\n index_offset_c = ctypes.c_ulong(index_offset)\n\n if read_data_type == PLCTYPE_STRING:\n read_data = (STRING_BUFFER * PLCTYPE_STRING)()\n else:\n read_data = read_data_type()\n\n read_data_pointer = ctypes.pointer(read_data)\n read_length = ctypes.c_ulong(ctypes.sizeof(read_data))\n\n bytes_read = ctypes.c_ulong()\n bytes_read_pointer = ctypes.pointer(bytes_read)\n\n if write_data_type == PLCTYPE_STRING:\n # Get pointer to string\n write_data_pointer = ctypes.c_char_p(\n value.encode(\"utf-8\")\n ) # type: Union[ctypes.c_char_p, ctypes.pointer] # noqa: E501\n # Add an extra byte to the data length for the null terminator\n write_length = len(value) + 1\n else:\n if type(write_data_type).__name__ == \"PyCArrayType\":\n write_data = write_data_type(*value)\n else:\n write_data = write_data_type(value)\n write_data_pointer = ctypes.pointer(write_data)\n write_length = ctypes.sizeof(write_data)\n\n err_code = sync_read_write_request(\n port,\n ams_address_pointer,\n index_group_c,\n index_offset_c,\n read_length,\n read_data_pointer,\n write_length,\n write_data_pointer,\n bytes_read_pointer,\n )\n\n if err_code:\n raise ADSError(err_code)\n\n # If we're reading a value of predetermined size (anything but a string),\n # validate that the correct number of bytes were read\n if read_data_type != PLCTYPE_STRING and bytes_read.value != read_length.value:\n raise RuntimeError(\n \"Insufficient data (expected {0} bytes, {1} were read).\".format(\n read_length.value, bytes_read.value\n )\n )\n\n if return_ctypes:\n return read_data\n\n if read_data_type == PLCTYPE_STRING:\n return read_data.value.decode(\"utf-8\")\n\n if type(read_data_type).__name__ == \"PyCArrayType\":\n return [i for i in read_data]\n\n if hasattr(read_data, \"value\"):\n return read_data.value\n\n return read_data"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef adsSyncReadReqEx2(\n port, address, index_group, index_offset, data_type, return_ctypes=False\n):\n # type: (int, AmsAddr, int, int, Type, bool) -> Any\n \"\"\"Read data synchronous from an ADS-device.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param pyads.structs.AmsAddr address: local or remote AmsAddr\n :param int index_group: PLC storage area, according to the INDEXGROUP\n constants\n :param int index_offset: PLC storage address\n :param Type data_type: type of the data given to the PLC, according to\n PLCTYPE constants\n :param bool return_ctypes: return ctypes instead of python types if True\n (default: False)\n :rtype: data_type\n :return: value: **value**\n\n \"\"\"\n sync_read_request = _adsDLL.AdsSyncReadReqEx2\n\n ams_address_pointer = ctypes.pointer(address.amsAddrStruct())\n index_group_c = ctypes.c_ulong(index_group)\n index_offset_c = ctypes.c_ulong(index_offset)\n\n if data_type == PLCTYPE_STRING:\n data = (STRING_BUFFER * PLCTYPE_STRING)()\n else:\n data = data_type()\n\n data_pointer = ctypes.pointer(data)\n data_length = ctypes.c_ulong(ctypes.sizeof(data))\n\n bytes_read = ctypes.c_ulong()\n bytes_read_pointer = ctypes.pointer(bytes_read)\n\n error_code = sync_read_request(\n port,\n ams_address_pointer,\n index_group_c,\n index_offset_c,\n data_length,\n data_pointer,\n bytes_read_pointer,\n )\n\n if error_code:\n raise ADSError(error_code)\n\n # If we're reading a value of predetermined size (anything but a string),\n # validate that the correct number of bytes were read\n if data_type != PLCTYPE_STRING and bytes_read.value != data_length.value:\n raise RuntimeError(\n \"Insufficient data (expected {0} bytes, {1} were read).\".format(\n data_length.value, bytes_read.value\n )\n )\n\n if return_ctypes:\n return data\n\n if data_type == PLCTYPE_STRING:\n return data.value.decode(\"utf-8\")\n\n if type(data_type).__name__ == \"PyCArrayType\":\n return [i for i in data]\n\n if hasattr(data, \"value\"):\n return data.value\n\n return data", "response": "Reads data from an AMS - device and returns the result as a Python object."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef adsSyncReadByNameEx(port, address, data_name, data_type, return_ctypes=False):\n # type: (int, AmsAddr, str, Type, bool) -> Any\n \"\"\"Read data synchronous from an ADS-device from data name.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param pyads.structs.AmsAddr address: local or remote AmsAddr\n :param string data_name: data name\n :param Type data_type: type of the data given to the PLC, according to\n PLCTYPE constants\n :param bool return_ctypes: return ctypes instead of python types if True\n (default: False)\n :rtype: data_type\n :return: value: **value**\n\n \"\"\"\n # Get the handle of the PLC-variable\n handle = adsSyncReadWriteReqEx2(\n port,\n address,\n ADSIGRP_SYM_HNDBYNAME,\n 0x0,\n PLCTYPE_UDINT,\n data_name,\n PLCTYPE_STRING,\n )\n\n # Read the value of a PLC-variable, via handle\n value = adsSyncReadReqEx2(\n port, address, ADSIGRP_SYM_VALBYHND, handle, data_type, return_ctypes\n )\n\n # Release the handle of the PLC-variable\n adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT)\n\n return value", "response": "Reads data from an ADS - device from data name."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef adsSyncWriteByNameEx(port, address, data_name, value, data_type):\n # type: (int, AmsAddr, str, Any, Type) -> None\n \"\"\"Send data synchronous to an ADS-device from data name.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param pyads.structs.AmsAddr address: local or remote AmsAddr\n :param string data_name: PLC storage address\n :param value: value to write to the storage address of the PLC\n :param Type data_type: type of the data given to the PLC,\n according to PLCTYPE constants\n\n \"\"\"\n # Get the handle of the PLC-variable\n handle = adsSyncReadWriteReqEx2(\n port,\n address,\n ADSIGRP_SYM_HNDBYNAME,\n 0x0,\n PLCTYPE_UDINT,\n data_name,\n PLCTYPE_STRING,\n )\n\n # Write the value of a PLC-variable, via handle\n adsSyncWriteReqEx(port, address, ADSIGRP_SYM_VALBYHND, handle, value, data_type)\n\n # Release the handle of the PLC-variable\n adsSyncWriteReqEx(port, address, ADSIGRP_SYM_RELEASEHND, 0, handle, PLCTYPE_UDINT)", "response": "Send data synchronous to an AMS - device from data name."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nadd a device notification to the AMS.", "response": "def adsSyncAddDeviceNotificationReqEx(\n port, adr, data_name, pNoteAttrib, callback, user_handle=None\n):\n # type: (int, AmsAddr, str, NotificationAttrib, Callable, int) -> Tuple[int, int]\n \"\"\"Add a device notification.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n :param string data_name: PLC storage address\n :param pyads.structs.NotificationAttrib pNoteAttrib: notification attributes\n :param callback: Callback function to handle notification\n :param user_handle: User Handle\n :rtype: (int, int)\n :returns: notification handle, user handle\n\n \"\"\"\n global callback_store\n\n if NOTEFUNC is None:\n raise TypeError(\"Callback function type can't be None\")\n\n adsSyncAddDeviceNotificationReqFct = _adsDLL.AdsSyncAddDeviceNotificationReqEx\n\n pAmsAddr = ctypes.pointer(adr.amsAddrStruct())\n hnl = adsSyncReadWriteReqEx2(\n port, adr, ADSIGRP_SYM_HNDBYNAME, 0x0, PLCTYPE_UDINT, data_name, PLCTYPE_STRING\n )\n\n nIndexGroup = ctypes.c_ulong(ADSIGRP_SYM_VALBYHND)\n nIndexOffset = ctypes.c_ulong(hnl)\n attrib = pNoteAttrib.notificationAttribStruct()\n pNotification = ctypes.c_ulong()\n\n nHUser = ctypes.c_ulong(hnl)\n if user_handle is not None:\n nHUser = ctypes.c_ulong(user_handle)\n\n adsSyncAddDeviceNotificationReqFct.argtypes = [\n ctypes.c_ulong,\n ctypes.POINTER(SAmsAddr),\n ctypes.c_ulong,\n ctypes.c_ulong,\n ctypes.POINTER(SAdsNotificationAttrib),\n NOTEFUNC,\n ctypes.c_ulong,\n ctypes.POINTER(ctypes.c_ulong),\n ]\n adsSyncAddDeviceNotificationReqFct.restype = ctypes.c_long\n\n def wrapper(addr, notification, user):\n # type: (AmsAddr, SAdsNotificationHeader, int) -> Callable[[SAdsNotificationHeader, str], None]\n return callback(notification, data_name)\n\n c_callback = NOTEFUNC(wrapper)\n err_code = adsSyncAddDeviceNotificationReqFct(\n port,\n pAmsAddr,\n nIndexGroup,\n nIndexOffset,\n ctypes.byref(attrib),\n c_callback,\n nHUser,\n ctypes.byref(pNotification),\n )\n\n if err_code:\n raise ADSError(err_code)\n callback_store[pNotification.value] = c_callback\n return (pNotification.value, hnl)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nremoving a device notification.", "response": "def adsSyncDelDeviceNotificationReqEx(port, adr, notification_handle, user_handle):\n # type: (int, AmsAddr, int, int) -> None\n \"\"\"Remove a device notification.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param pyads.structs.AmsAddr adr: local or remote AmsAddr\n :param int notification_handle: Notification Handle\n :param int user_handle: User Handle\n\n \"\"\"\n adsSyncDelDeviceNotificationReqFct = _adsDLL.AdsSyncDelDeviceNotificationReqEx\n\n pAmsAddr = ctypes.pointer(adr.amsAddrStruct())\n nHNotification = ctypes.c_ulong(notification_handle)\n err_code = adsSyncDelDeviceNotificationReqFct(port, pAmsAddr, nHNotification)\n callback_store.pop(notification_handle, None)\n if err_code:\n raise ADSError(err_code)\n\n adsSyncWriteReqEx(port, adr, ADSIGRP_SYM_RELEASEHND, 0, user_handle, PLCTYPE_UDINT)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef adsSyncSetTimeoutEx(port, nMs):\n # type: (int, int) -> None\n \"\"\"Set Timeout.\n\n :param int port: local AMS port as returned by adsPortOpenEx()\n :param int nMs: timeout in ms\n\n \"\"\"\n adsSyncSetTimeoutFct = _adsDLL.AdsSyncSetTimeoutEx\n cms = ctypes.c_long(nMs)\n err_code = adsSyncSetTimeoutFct(port, cms)\n if err_code:\n raise ADSError(err_code)", "response": "Sets the ADS server to timeout in ms."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef _parse_ams_netid(ams_netid):\r\n # type: (str) -> SAmsNetId\r\n \"\"\"Parse an AmsNetId from *str* to *SAmsNetId*.\r\n\r\n :param str ams_netid: NetId as a string\r\n :rtype: SAmsNetId\r\n :return: NetId as a struct\r\n\r\n \"\"\"\r\n try:\r\n id_numbers = list(map(int, ams_netid.split(\".\")))\r\n except ValueError:\r\n raise ValueError(\"no valid netid\")\r\n\r\n if len(id_numbers) != 6:\r\n raise ValueError(\"no valid netid\")\r\n\r\n # Fill the netId struct with data\r\n ams_netid_st = SAmsNetId()\r\n ams_netid_st.b = (c_ubyte * 6)(*id_numbers)\r\n return ams_netid_st", "response": "Parse an AmsNetId from a string to a SAmsNetId."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef set_local_address(ams_netid):\r\n # type: (Union[str, SAmsNetId]) -> None\r\n \"\"\"Set the local NetID (**Linux only**).\r\n\r\n :param str: new AmsNetID\r\n :rtype: None\r\n\r\n **Usage:**\r\n\r\n >>> import pyads\r\n >>> pyads.open_port()\r\n >>> pyads.set_local_address('0.0.0.0.1.1')\r\n\r\n \"\"\"\r\n if isinstance(ams_netid, str):\r\n ams_netid_st = _parse_ams_netid(ams_netid)\r\n else:\r\n ams_netid_st = ams_netid\r\n\r\n assert isinstance(ams_netid_st, SAmsNetId)\r\n\r\n if linux:\r\n return adsSetLocalAddress(ams_netid_st)\r\n else:\r\n raise ADSError(\r\n text=\"SetLocalAddress is not supported for Windows clients.\"\r\n )", "response": "Set the local address of the given AMS NetID."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef write_control(adr, ads_state, device_state, data, plc_datatype):\r\n # type: (AmsAddr, int, int, Any, Type) -> None\r\n \"\"\"Change the ADS state and the machine-state of the ADS-server.\r\n\r\n :param AmsAddr adr: local or remote AmsAddr\r\n :param int ads_state: new ADS-state, according to ADSTATE constants\r\n :param int device_state: new machine-state\r\n :param data: additional data\r\n :param int plc_datatype: datatype, according to PLCTYPE constants\r\n\r\n :note: Despite changing the ADS-state and the machine-state it is possible\r\n to send additional data to the ADS-server. For current ADS-devices\r\n additional data is not progressed.\r\n Every ADS-device is able to communicate its current state to other\r\n devices.\r\n There is a difference between the device-state and the state of the\r\n ADS-interface (AdsState). The possible states of an ADS-interface\r\n are defined in the ADS-specification.\r\n\r\n \"\"\"\r\n if port is not None:\r\n return adsSyncWriteControlReqEx(\r\n port, adr, ads_state, device_state, data, plc_datatype\r\n )", "response": "Write the control to the ADS server."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef write(adr, index_group, index_offset, value, plc_datatype):\r\n # type: (AmsAddr, int, int, Any, Type) -> None\r\n \"\"\"Send data synchronous to an ADS-device.\r\n\r\n :param AmsAddr adr: local or remote AmsAddr\r\n :param int index_group: PLC storage area, according to the INDEXGROUP\r\n constants\r\n :param int index_offset: PLC storage address\r\n :param value: value to write to the storage address of the PLC\r\n :param Type plc_datatype: type of the data given to the PLC,\r\n according to PLCTYPE constants\r\n\r\n \"\"\"\r\n if port is not None:\r\n return adsSyncWriteReqEx(\r\n port, adr, index_group, index_offset, value, plc_datatype\r\n )", "response": "Send data synchronous to an ADS - device."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nread and writes data synchronous from an ADS - device.", "response": "def read_write(\r\n adr,\r\n index_group,\r\n index_offset,\r\n plc_read_datatype,\r\n value,\r\n plc_write_datatype,\r\n return_ctypes=False,\r\n):\r\n # type: (AmsAddr, int, int, Type, Any, Type, bool) -> Any\r\n \"\"\"Read and write data synchronous from/to an ADS-device.\r\n\r\n :param AmsAddr adr: local or remote AmsAddr\r\n :param int index_group: PLC storage area, according to the INDEXGROUP\r\n constants\r\n :param int index_offset: PLC storage address\r\n :param Type plc_read_datatype: type of the data given to the PLC to respond\r\n to, according to PLCTYPE constants\r\n :param value: value to write to the storage address of the PLC\r\n :param Type plc_write_datatype: type of the data given to the PLC, according to\r\n PLCTYPE constants\r\n :param bool return_ctypes: return ctypes instead of python types if True\r\n (default: False)\r\n :rtype: PLCTYPE\r\n :return: value: **value**\r\n\r\n \"\"\"\r\n if port is not None:\r\n return adsSyncReadWriteReqEx2(\r\n port,\r\n adr,\r\n index_group,\r\n index_offset,\r\n plc_read_datatype,\r\n value,\r\n plc_write_datatype,\r\n return_ctypes,\r\n )\r\n\r\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef read(adr, index_group, index_offset, plc_datatype, return_ctypes=False):\r\n # type: (AmsAddr, int, int, Type, bool) -> Any\r\n \"\"\"Read data synchronous from an ADS-device.\r\n\r\n :param AmsAddr adr: local or remote AmsAddr\r\n :param int index_group: PLC storage area, according to the INDEXGROUP\r\n constants\r\n :param int index_offset: PLC storage address\r\n :param int plc_datatype: type of the data given to the PLC, according to\r\n PLCTYPE constants\r\n :param bool return_ctypes: return ctypes instead of python types if True\r\n (default: False)\r\n :return: value: **value**\r\n\r\n \"\"\"\r\n if port is not None:\r\n return adsSyncReadReqEx2(\r\n port, adr, index_group, index_offset, plc_datatype, return_ctypes\r\n )\r\n\r\n return None", "response": "Read data synchronous from an ADS - device."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef read_by_name(adr, data_name, plc_datatype, return_ctypes=False):\r\n # type: (AmsAddr, str, Type, bool) -> Any\r\n \"\"\"Read data synchronous from an ADS-device from data name.\r\n\r\n :param AmsAddr adr: local or remote AmsAddr\r\n :param string data_name: data name\r\n :param int plc_datatype: type of the data given to the PLC, according to\r\n PLCTYPE constants\r\n :param bool return_ctypes: return ctypes instead of python types if True\r\n (default: False)\r\n :return: value: **value**\r\n\r\n \"\"\"\r\n if port is not None:\r\n return adsSyncReadByNameEx(port, adr, data_name, plc_datatype, return_ctypes)\r\n\r\n return None", "response": "Reads data from an ADS - device from a data name."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nsends data synchronous to an ADS - device from data name.", "response": "def write_by_name(adr, data_name, value, plc_datatype):\r\n # type: (AmsAddr, str, Any, Type) -> None\r\n \"\"\"Send data synchronous to an ADS-device from data name.\r\n\r\n :param AmsAddr adr: local or remote AmsAddr\r\n :param string data_name: PLC storage address\r\n :param value: value to write to the storage address of the PLC\r\n :param int plc_datatype: type of the data given to the PLC,\r\n according to PLCTYPE constants\r\n\r\n \"\"\"\r\n if port is not None:\r\n return adsSyncWriteByNameEx(port, adr, data_name, value, plc_datatype)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef add_device_notification(adr, data_name, attr, callback, user_handle=None):\r\n # type: (AmsAddr, str, NotificationAttrib, Callable, int) -> Optional[Tuple[int, int]] # noqa: E501\r\n \"\"\"Add a device notification.\r\n\r\n :param pyads.structs.AmsAddr adr: AMS Address associated with the routing\r\n entry which is to be removed from the router.\r\n :param str data_name: PLC storage address\r\n :param pyads.structs.NotificationAttrib attr: object that contains\r\n all the attributes for the definition of a notification\r\n :param callback: callback function that gets executed on in the event\r\n of a notification\r\n\r\n :rtype: (int, int)\r\n :returns: notification handle, user handle\r\n\r\n Save the notification handle and the user handle on creating a\r\n notification if you want to be able to remove the notification\r\n later in your code.\r\n\r\n \"\"\"\r\n if port is not None:\r\n return adsSyncAddDeviceNotificationReqEx(\r\n port, adr, data_name, attr, callback, user_handle\r\n )\r\n\r\n return None", "response": "Add a device notification."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nremoving a device notification from the routing table.", "response": "def del_device_notification(adr, notification_handle, user_handle):\r\n # type: (AmsAddr, int, int) -> None\r\n \"\"\"Remove a device notification.\r\n\r\n :param pyads.structs.AmsAddr adr: AMS Address associated with the routing\r\n entry which is to be removed from the router.\r\n :param notification_handle: address of the variable that contains\r\n the handle of the notification\r\n :param user_handle: user handle\r\n\r\n \"\"\"\r\n if port is not None:\r\n return adsSyncDelDeviceNotificationReqEx(\r\n port, adr, notification_handle, user_handle\r\n )"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef open(self):\r\n # type: () -> None\r\n \"\"\"Connect to the TwinCAT message router.\"\"\"\r\n if self._open:\r\n return\r\n\r\n self._port = adsPortOpenEx()\r\n\r\n if linux:\r\n adsAddRoute(self._adr.netIdStruct(), self.ip_address)\r\n\r\n self._open = True", "response": "Connect to the TwinCAT message router."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nclosing the connection to the TwinCAT message router.", "response": "def close(self):\r\n # type: () -> None\r\n \"\"\":summary: Close the connection to the TwinCAT message router.\"\"\"\r\n if not self._open:\r\n return\r\n\r\n if linux:\r\n adsDelRoute(self._adr.netIdStruct())\r\n\r\n if self._port is not None:\r\n adsPortCloseEx(self._port)\r\n self._port = None\r\n\r\n self._open = False"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef write_control(self, ads_state, device_state, data, plc_datatype):\r\n # type: (int, int, Any, Type) -> None\r\n \"\"\"Change the ADS state and the machine-state of the ADS-server.\r\n\r\n :param int ads_state: new ADS-state, according to ADSTATE constants\r\n :param int device_state: new machine-state\r\n :param data: additional data\r\n :param int plc_datatype: datatype, according to PLCTYPE constants\r\n\r\n :note: Despite changing the ADS-state and the machine-state it is\r\n possible to send additional data to the ADS-server. For current\r\n ADS-devices additional data is not progressed.\r\n Every ADS-device is able to communicate its current state to other\r\n devices. There is a difference between the device-state and the\r\n state of the ADS-interface (AdsState). The possible states of an\r\n ADS-interface are defined in the ADS-specification.\r\n\r\n \"\"\"\r\n if self._port is not None:\r\n return adsSyncWriteControlReqEx(\r\n self._port, self._adr, ads_state, device_state, data, plc_datatype\r\n )", "response": "Write the control of an ADS - server."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef write(self, index_group, index_offset, value, plc_datatype):\r\n # type: (int, int, Any, Type) -> None\r\n \"\"\"Send data synchronous to an ADS-device.\r\n\r\n :param int index_group: PLC storage area, according to the INDEXGROUP\r\n constants\r\n :param int index_offset: PLC storage address\r\n :param value: value to write to the storage address of the PLC\r\n :param int plc_datatype: type of the data given to the PLC,\r\n according to PLCTYPE constants\r\n\r\n \"\"\"\r\n if self._port is not None:\r\n return adsSyncWriteReqEx(\r\n self._port, self._adr, index_group, index_offset, value, plc_datatype\r\n )", "response": "Send data synchronous to an ADS - device."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreads and writes the specified value from an ADS - device and returns the result.", "response": "def read_write(\r\n self,\r\n index_group,\r\n index_offset,\r\n plc_read_datatype,\r\n value,\r\n plc_write_datatype,\r\n return_ctypes=False,\r\n ):\r\n # type: (int, int, Type, Any, Type, bool) -> Any\r\n \"\"\"Read and write data synchronous from/to an ADS-device.\r\n\r\n :param int index_group: PLC storage area, according to the INDEXGROUP\r\n constants\r\n :param int index_offset: PLC storage address\r\n :param int plc_read_datatype: type of the data given to the PLC to\r\n respond to, according to PLCTYPE constants\r\n :param value: value to write to the storage address of the PLC\r\n :param plc_write_datatype: type of the data given to the PLC,\r\n according to PLCTYPE constants\r\n :rtype: PLCTYPE\r\n :param bool return_ctypes: return ctypes instead of python types if True\r\n (default: False)\r\n :return: value: **value**\r\n\r\n \"\"\"\r\n if self._port is not None:\r\n return adsSyncReadWriteReqEx2(\r\n self._port,\r\n self._adr,\r\n index_group,\r\n index_offset,\r\n plc_read_datatype,\r\n value,\r\n plc_write_datatype,\r\n return_ctypes,\r\n )\r\n\r\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreading data synchronous from an ADS - device.", "response": "def read(self, index_group, index_offset, plc_datatype, return_ctypes=False):\r\n # type: (int, int, Type, bool) -> Any\r\n \"\"\"Read data synchronous from an ADS-device.\r\n\r\n :param int index_group: PLC storage area, according to the INDEXGROUP\r\n constants\r\n :param int index_offset: PLC storage address\r\n :param int plc_datatype: type of the data given to the PLC, according\r\n to PLCTYPE constants\r\n :return: value: **value**\r\n :param bool return_ctypes: return ctypes instead of python types if True\r\n (default: False)\r\n\r\n \"\"\"\r\n if self._port is not None:\r\n return adsSyncReadReqEx2(\r\n self._port, self._adr, index_group, index_offset, plc_datatype, return_ctypes\r\n )\r\n\r\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef read_by_name(self, data_name, plc_datatype, return_ctypes=False):\r\n # type: (str, Type, bool) -> Any\r\n \"\"\"Read data synchronous from an ADS-device from data name.\r\n\r\n :param string data_name: data name\r\n :param int plc_datatype: type of the data given to the PLC, according\r\n to PLCTYPE constants\r\n :return: value: **value**\r\n :param bool return_ctypes: return ctypes instead of python types if True\r\n (default: False)\r\n\r\n \"\"\"\r\n if self._port:\r\n return adsSyncReadByNameEx(self._port, self._adr, data_name, plc_datatype, return_ctypes)\r\n\r\n return None", "response": "Reads data from an ADS - device from a data name."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef write_by_name(self, data_name, value, plc_datatype):\r\n # type: (str, Any, Type) -> None\r\n \"\"\"Send data synchronous to an ADS-device from data name.\r\n\r\n :param string data_name: PLC storage address\r\n :param value: value to write to the storage address of the PLC\r\n :param int plc_datatype: type of the data given to the PLC,\r\n according to PLCTYPE constants\r\n\r\n \"\"\"\r\n if self._port:\r\n return adsSyncWriteByNameEx(\r\n self._port, self._adr, data_name, value, plc_datatype\r\n )", "response": "Send data synchronous to an ADS - device from data name."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nadd a new device notification.", "response": "def add_device_notification(self, data_name, attr, callback, user_handle=None):\r\n # type: (str, NotificationAttrib, Callable, int) -> Optional[Tuple[int, int]]\r\n \"\"\"Add a device notification.\r\n\r\n :param str data_name: PLC storage address\r\n :param pyads.structs.NotificationAttrib attr: object that contains\r\n all the attributes for the definition of a notification\r\n :param callback: callback function that gets executed on in the event\r\n of a notification\r\n\r\n :rtype: (int, int)\r\n :returns: notification handle, user handle\r\n\r\n Save the notification handle and the user handle on creating a\r\n notification if you want to be able to remove the notification\r\n later in your code.\r\n\r\n **Usage**:\r\n\r\n >>> import pyads\r\n >>> from ctypes import size_of\r\n >>>\r\n >>> # Connect to the local TwinCAT PLC\r\n >>> plc = pyads.Connection('127.0.0.1.1.1', 851)\r\n >>>\r\n >>> # Create callback function that prints the value\r\n >>> def mycallback(adr, notification, user):\r\n >>> contents = notification.contents\r\n >>> value = next(\r\n >>> map(int,\r\n >>> bytearray(contents.data)[0:contents.cbSampleSize])\r\n >>> )\r\n >>> print(value)\r\n >>>\r\n >>> with plc:\r\n >>> # Add notification with default settings\r\n >>> attr = pyads.NotificationAttrib(size_of(pyads.PLCTYPE_INT))\r\n >>>\r\n >>> hnotification, huser = plc.add_device_notification(\r\n >>> adr, attr, mycallback)\r\n >>>\r\n >>> # Remove notification\r\n >>> plc.del_device_notification(hnotification, huser)\r\n\r\n \"\"\"\r\n if self._port is not None:\r\n notification_handle, user_handle = adsSyncAddDeviceNotificationReqEx(\r\n self._port, self._adr, data_name, attr, callback, user_handle\r\n )\r\n return notification_handle, user_handle\r\n\r\n return None"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef del_device_notification(self, notification_handle, user_handle):\r\n # type: (int, int) -> None\r\n \"\"\"Remove a device notification.\r\n\r\n :param notification_handle: address of the variable that contains\r\n the handle of the notification\r\n :param user_handle: user handle\r\n\r\n \"\"\"\r\n if self._port is not None:\r\n adsSyncDelDeviceNotificationReqEx(\r\n self._port, self._adr, notification_handle, user_handle\r\n )", "response": "Remove a device notification."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef notification(self, plc_datatype=None):\r\n # type: (Optional[Type[Any]]) -> Callable\r\n \"\"\"Decorate a callback function.\r\n\r\n **Decorator**.\r\n\r\n A decorator that can be used for callback functions in order to\r\n convert the data of the NotificationHeader into the fitting\r\n Python type.\r\n\r\n :param plc_datatype: The PLC datatype that needs to be converted. This can\r\n be any basic PLC datatype or a `ctypes.Structure`.\r\n\r\n The callback functions need to be of the following type:\r\n\r\n >>> def callback(handle, name, timestamp, value)\r\n\r\n * `handle`: the notification handle\r\n * `name`: the variable name\r\n * `timestamp`: the timestamp as datetime value\r\n * `value`: the converted value of the variable\r\n\r\n **Usage**:\r\n\r\n >>> import pyads\r\n >>>\r\n >>> plc = pyads.Connection('172.18.3.25.1.1', 851)\r\n >>>\r\n >>>\r\n >>> @plc.notification(pyads.PLCTYPE_STRING)\r\n >>> def callback(handle, name, timestamp, value):\r\n >>> print(handle, name, timestamp, value)\r\n >>>\r\n >>>\r\n >>> with plc:\r\n >>> attr = pyads.NotificationAttrib(20,\r\n >>> pyads.ADSTRANS_SERVERCYCLE)\r\n >>> handles = plc.add_device_notification('GVL.test', attr,\r\n >>> callback)\r\n >>> while True:\r\n >>> pass\r\n\r\n \"\"\"\r\n\r\n def notification_decorator(func):\r\n # type: (Callable[[int, str, datetime, Any], None]) -> Callable[[Any, str], None] # noqa: E501\r\n\r\n def func_wrapper(notification, data_name):\r\n # type: (Any, str) -> None\r\n contents = notification.contents\r\n data = contents.data\r\n data_size = contents.cbSampleSize\r\n\r\n datatype_map = {\r\n PLCTYPE_BOOL: \"\",\r\n PLCTYPE_BYTE: \" {}\".format(len(deputies), start_date, end_date))\n\n records = self._all_presences(deputies, start_date, end_date)\n\n df = pd.DataFrame(records, columns=(\n 'term',\n 'congressperson_document',\n 'congressperson_name',\n 'party',\n 'state',\n 'date',\n 'present_on_day',\n 'justification',\n 'session',\n 'presence'\n ))\n return self._translate(df)"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nfetch the official Missions from the specified date range.", "response": "def fetch_official_missions(data_dir, start_date, end_date):\n \"\"\"\n :param data_dir: (str) directory in which the output file will be saved\n :param start_date: (datetime) first date of the range to be scraped\n :param end_date: (datetime) last date of the range to be scraped\n \"\"\"\n official_missions = OfficialMissionsDataset()\n df = official_missions.fetch(start_date, end_date)\n save_to_csv(df, data_dir, \"official-missions\")\n\n return df"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nfetch official missions within the given date range", "response": "def fetch(self, start_date, end_date):\n \"\"\"\n Fetches official missions within the given date range\n \"\"\"\n\n records = []\n for two_months_range in self._generate_ranges(start_date, end_date):\n log.debug(two_months_range)\n for record in self._fetch_missions_for_range(two_months_range[0], two_months_range[1]):\n records.append(record)\n\n df = pd.DataFrame(records, columns=[\n 'participant',\n 'destination',\n 'subject',\n 'start',\n 'end',\n 'canceled',\n 'report_status',\n 'report_details_link'\n ])\n\n translate_column(df, 'report_status', {\n 'Dispon\u00edvel': 'Available',\n 'Pendente': 'Pending',\n 'Em an\u00e1lise': 'Analysing',\n 'N\u00e3o se aplica': 'Does not apply'\n })\n translate_column(df, 'canceled', {\n 'N\u00e3o': 'No',\n 'Sim': 'Yes'\n })\n\n return df.drop_duplicates()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _generate_ranges(start_date, end_date):\n range_start = start_date\n while range_start < end_date:\n range_end = range_start + timedelta(days=60)\n yield (\n range_start.strftime(\"%d/%m/%Y\"),\n range_end.strftime(\"%d/%m/%Y\")\n )\n range_start += timedelta(days=30)", "response": "Generate a list of 2 month ranges for the requested anracatetime."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef fetch_session_start_times(data_dir, pivot, session_dates):\n session_start_times = SessionStartTimesDataset()\n df = session_start_times.fetch(pivot, session_dates)\n save_to_csv(df, data_dir, \"session-start-times\")\n\n log.info(\"Dates requested:\", len(session_dates))\n found = pd.to_datetime(df['date'], format=\"%Y-%m-%d %H:%M:%S\").dt.date.unique()\n log.info(\"Dates found:\", len(found))\n return df", "response": "Fetch the start times for a congressperson document."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nfetches the start times for a congressperson document.", "response": "def fetch(self, pivot, session_dates):\n \"\"\"\n :param pivot: (int) a congressperson document to use as a pivot for scraping the data\n :param session_dates: (list) datetime objects to fetch the start times for\n \"\"\"\n\n records = self._all_start_times(pivot, session_dates)\n return pd.DataFrame(records, columns=(\n 'date',\n 'session',\n 'started_at'\n ))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef fetch_deputies(data_dir):\n deputies = DeputiesDataset()\n df = deputies.fetch()\n save_to_csv(df, data_dir, \"deputies\")\n\n holders = df.condition == 'Holder'\n substitutes = df.condition == 'Substitute'\n log.info(\"Total deputies:\", len(df))\n log.info(\"Holder deputies:\", len(df[holders]))\n log.info(\"Substitute deputies:\", len(df[substitutes]))\n return df", "response": "Fetch the deputies dataset and save it to a CSV file"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef fetch(self):\n xml = urllib.request.urlopen(self.URL)\n\n tree = ET.ElementTree(file=xml)\n records = self._parse_deputies(tree.getroot())\n\n df = pd.DataFrame(records, columns=(\n 'congressperson_id',\n 'budget_id',\n 'condition',\n 'congressperson_document',\n 'civil_name',\n 'congressperson_name',\n 'picture_url',\n 'gender',\n 'state',\n 'party',\n 'phone_number',\n 'email'\n ))\n return self._translate(df)", "response": "Fetches the list of deputies for the current term."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nadds a node to the hash ring including a number of replicas.", "response": "def add_node(self, node):\n \"\"\"Adds a `node` to the hash ring (including a number of replicas).\n \"\"\"\n self.nodes.append(node)\n for x in xrange(self.replicas):\n ring_key = self.hash_method(b(\"%s:%d\" % (node, x)))\n self.ring[ring_key] = node\n self.sorted_keys.append(ring_key)\n\n self.sorted_keys.sort()"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef remove_node(self, node):\n self.nodes.remove(node)\n for x in xrange(self.replicas):\n ring_key = self.hash_method(b(\"%s:%d\" % (node, x)))\n self.ring.pop(ring_key)\n self.sorted_keys.remove(ring_key)", "response": "Removes a node from the hash ring and its replicas."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_node_pos(self, key):\n if len(self.ring) == 0:\n return [None, None]\n crc = self.hash_method(b(key))\n idx = bisect.bisect(self.sorted_keys, crc)\n # prevents out of range index\n idx = min(idx, (self.replicas * len(self.nodes)) - 1)\n return [self.ring[self.sorted_keys[idx]], idx]", "response": "Given a string key returns a tuple of the node and its index in the hash ring along with its position in the ring."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef iter_nodes(self, key):\n if len(self.ring) == 0:\n yield None, None\n node, pos = self.get_node_pos(key)\n for k in self.sorted_keys[pos:]:\n yield k, self.ring[k]", "response": "Given a string key it returns the nodes as a generator that can hold the key."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef format_servers(servers):\n configs = []\n if not isinstance(servers, list):\n raise ValueError(\"server's config must be list\")\n _type = type(servers[0])\n if _type == dict:\n return servers\n if (sys.version_info[0] == 3 and _type in [str, bytes]) \\\n or (sys.version_info[0] == 2 and _type in [str, unicode]):\n for config in servers:\n configs.append(parse_url(config))\n else:\n raise ValueError(\"invalid server config\")\n return configs", "response": "returns a list of servers in two kinds of format"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreturn a list of values ordered identically to keys", "response": "def mget(self, keys, *args):\n \"\"\"\n Returns a list of values ordered identically to ``keys``\n \"\"\"\n args = list_or_args(keys, args)\n server_keys = {}\n ret_dict = {}\n for key in args:\n server_name = self.get_server_name(key)\n server_keys[server_name] = server_keys.get(server_name, [])\n server_keys[server_name].append(key)\n for server_name, sub_keys in iteritems(server_keys):\n values = self.connections[server_name].mget(sub_keys)\n ret_dict.update(dict(zip(sub_keys, values)))\n result = []\n for key in args:\n result.append(ret_dict.get(key, None))\n return result"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef mset(self, mapping):\n servers = {}\n for key, value in mapping.items():\n server_name = self.get_server_name(key)\n servers.setdefault(server_name, [])\n servers[server_name].append((key, value))\n for name, items in servers.items():\n self.connections[name].mset(dict(items))\n return True", "response": "Sets each key in the mapping dict to its corresponding value."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn a new Lock object using the specified key name.", "response": "def lock(self, name, timeout=None, sleep=0.1):\n \"\"\"\n Return a new Lock object using key ``name`` that mimics\n the behavior of threading.Lock.\n\n If specified, ``timeout`` indicates a maximum life for the lock.\n By default, it will remain locked until release() is called.\n\n ``sleep`` indicates the amount of time to sleep per loop iteration\n when the lock is in blocking mode and another client is currently\n holding the lock.\n \"\"\"\n return Lock(self, name, timeout=timeout, sleep=sleep)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef parse_line(line, document=None):\n '''\n Return a language-server diagnostic from a line of the Mypy error report;\n optionally, use the whole document to provide more context on it.\n '''\n result = re.match(line_pattern, line)\n if result:\n _, lineno, offset, severity, msg = result.groups()\n lineno = int(lineno or 1)\n offset = int(offset or 0)\n errno = 2\n if severity == 'error':\n errno = 1\n diag = {\n 'source': 'mypy',\n 'range': {\n 'start': {'line': lineno - 1, 'character': offset},\n # There may be a better solution, but mypy does not provide end\n 'end': {'line': lineno - 1, 'character': offset + 1}\n },\n 'message': msg,\n 'severity': errno\n }\n if document:\n # although mypy does not provide the end of the affected range, we\n # can make a good guess by highlighting the word that Mypy flagged\n word = document.word_at_position(diag['range']['start'])\n if word:\n diag['range']['end']['character'] = (\n diag['range']['start']['character'] + len(word))\n\n return diag", "response": "Parse a line of the Mypy error report into a dictionary of language - server diagnostic information."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nestablishing a connection to the Lavalink server.", "response": "async def connect(self):\r\n \"\"\" Establishes a connection to the Lavalink server. \"\"\"\r\n await self._lavalink.bot.wait_until_ready()\r\n\r\n if self._ws and self._ws.open:\r\n log.debug('WebSocket still open, closing...')\r\n await self._ws.close()\r\n\r\n user_id = self._lavalink.bot.user.id\r\n shard_count = self._lavalink.bot.shard_count or self._shards\r\n\r\n headers = {\r\n 'Authorization': self._password,\r\n 'Num-Shards': shard_count,\r\n 'User-Id': str(user_id)\r\n }\r\n log.debug('Preparing to connect to Lavalink')\r\n log.debug(' with URI: {}'.format(self._uri))\r\n log.debug(' with headers: {}'.format(str(headers)))\r\n log.info('Connecting to Lavalink...')\r\n\r\n try:\r\n self._ws = await websockets.connect(self._uri, loop=self._loop, extra_headers=headers)\r\n except OSError as error:\r\n log.exception('Failed to connect to Lavalink: {}'.format(str(error)))\r\n else:\r\n log.info('Connected to Lavalink!')\r\n self._loop.create_task(self.listen())\r\n version = self._ws.response_headers.get('Lavalink-Major-Version', 2)\r\n try:\r\n self._lavalink._server_version = int(version)\r\n except ValueError:\r\n self._lavalink._server_version = 2\r\n log.info('Lavalink server version is {}'.format(version))\r\n if self._queue:\r\n log.info('Replaying {} queued events...'.format(len(self._queue)))\r\n for task in self._queue:\r\n await self.send(**task)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def _attempt_reconnect(self):\r\n log.info('Connection closed; attempting to reconnect in 30 seconds')\r\n for a in range(0, self._ws_retry):\r\n await asyncio.sleep(30)\r\n log.info('Reconnecting... (Attempt {})'.format(a + 1))\r\n await self.connect()\r\n\r\n if self._ws.open:\r\n return True\r\n return False", "response": "Attempts to reconnect to the Lavalink server."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nwaits for a message from the Lavalink server and processes it.", "response": "async def listen(self):\r\n \"\"\" Waits to receive a payload from the Lavalink server and processes it. \"\"\"\r\n while not self._shutdown:\r\n try:\r\n data = json.loads(await self._ws.recv())\r\n except websockets.ConnectionClosed as error:\r\n log.warning('Disconnected from Lavalink: {}'.format(str(error)))\r\n for g in self._lavalink.players._players.copy().keys():\r\n ws = self._lavalink.bot._connection._get_websocket(int(g))\r\n await ws.voice_state(int(g), None)\r\n\r\n self._lavalink.players.clear()\r\n\r\n if self._shutdown:\r\n break\r\n\r\n if await self._attempt_reconnect():\r\n return\r\n\r\n log.warning('Unable to reconnect to Lavalink!')\r\n break\r\n\r\n op = data.get('op', None)\r\n log.debug('Received WebSocket data {}'.format(str(data)))\r\n\r\n if not op:\r\n return log.debug('Received WebSocket message without op {}'.format(str(data)))\r\n\r\n if op == 'event':\r\n log.debug('Received event of type {}'.format(data['type']))\r\n player = self._lavalink.players[int(data['guildId'])]\r\n event = None\r\n\r\n if data['type'] == 'TrackEndEvent':\r\n event = TrackEndEvent(player, data['track'], data['reason'])\r\n elif data['type'] == 'TrackExceptionEvent':\r\n event = TrackExceptionEvent(player, data['track'], data['error'])\r\n elif data['type'] == 'TrackStuckEvent':\r\n event = TrackStuckEvent(player, data['track'], data['thresholdMs'])\r\n\r\n if event:\r\n await self._lavalink.dispatch_event(event)\r\n elif op == 'playerUpdate':\r\n await self._lavalink.update_state(data)\r\n elif op == 'stats':\r\n self._lavalink.stats._update(data)\r\n await self._lavalink.dispatch_event(StatsUpdateEvent(self._lavalink.stats))\r\n\r\n log.debug('Closing WebSocket...')\r\n await self._ws.close()"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef connected_channel(self):\r\n if not self.channel_id:\r\n return None\r\n\r\n return self._lavalink.bot.get_channel(int(self.channel_id))", "response": "Returns the voice channel that the player is connected to."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nconnect to a voice channel.", "response": "async def connect(self, channel_id: int):\r\n \"\"\" Connects to a voice channel. \"\"\"\r\n ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))\r\n await ws.voice_state(self.guild_id, str(channel_id))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndisconnecting from the voice channel if any.", "response": "async def disconnect(self):\r\n \"\"\" Disconnects from the voice channel, if any. \"\"\"\r\n if not self.is_connected:\r\n return\r\n\r\n await self.stop()\r\n\r\n ws = self._lavalink.bot._connection._get_websocket(int(self.guild_id))\r\n await ws.voice_state(self.guild_id, None)"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nstores custom user data.", "response": "def store(self, key: object, value: object):\r\n \"\"\" Stores custom user data. \"\"\"\r\n self._user_data.update({key: value})"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef fetch(self, key: object, default=None):\r\n return self._user_data.get(key, default)", "response": "Retrieves the related value for the given key from the stored user data."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nadd a track to the queue.", "response": "def add(self, requester: int, track: dict):\r\n \"\"\" Adds a track to the queue. \"\"\"\r\n self.queue.append(AudioTrack().build(track, requester))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef add_next(self, requester: int, track: dict):\r\n self.queue.insert(0, AudioTrack().build(track, requester))", "response": "Adds a track to the beginning of the queue"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef add_at(self, index: int, requester: int, track: dict):\r\n self.queue.insert(min(index, len(self.queue) - 1), AudioTrack().build(track, requester))", "response": "Adds a track at a specific index in the queue."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nplays the first track in the queue if any or plays a track from the specified index.", "response": "async def play(self, track_index: int = 0, ignore_shuffle: bool = False):\r\n \"\"\" Plays the first track in the queue, if any or plays a track from the specified index in the queue. \"\"\"\r\n if self.repeat and self.current:\r\n self.queue.append(self.current)\r\n\r\n self.previous = self.current\r\n self.current = None\r\n self.position = 0\r\n self.paused = False\r\n\r\n if not self.queue:\r\n await self.stop()\r\n await self._lavalink.dispatch_event(QueueEndEvent(self))\r\n else:\r\n if self.shuffle and not ignore_shuffle:\r\n track = self.queue.pop(randrange(len(self.queue)))\r\n else:\r\n track = self.queue.pop(min(track_index, len(self.queue) - 1))\r\n\r\n self.current = track\r\n await self._lavalink.ws.send(op='play', guildId=self.guild_id, track=track.track)\r\n await self._lavalink.dispatch_event(TrackStartEvent(self, track))"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\nasync def play_now(self, requester: int, track: dict):\r\n self.add_next(requester, track)\r\n await self.play(ignore_shuffle=True)", "response": "Add a new track and play it."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\nasync def play_at(self, index: int):\r\n self.queue = self.queue[min(index, len(self.queue) - 1):len(self.queue)]\r\n await self.play(ignore_shuffle=True)", "response": "Play the queue from a specific point. Disregards tracks before the index."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nplays the previous track if it exists.", "response": "async def play_previous(self):\r\n \"\"\" Plays previous track if it exist, if it doesn't raises a NoPreviousTrack error. \"\"\"\r\n if not self.previous:\r\n raise NoPreviousTrack\r\n self.queue.insert(0, self.previous)\r\n await self.play(ignore_shuffle=True)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def stop(self):\r\n await self._lavalink.ws.send(op='stop', guildId=self.guild_id)\r\n self.current = None", "response": "Stops the player if playing."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\nasync def set_pause(self, pause: bool):\r\n await self._lavalink.ws.send(op='pause', guildId=self.guild_id, pause=pause)\r\n self.paused = pause", "response": "Sets the player s paused state."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\nasync def set_volume(self, vol: int):\r\n if self._lavalink._server_version <= 2:\r\n self.volume = max(min(vol, 150), 0)\r\n else:\r\n self.volume = max(min(vol, 1000), 0)\r\n await self._lavalink.ws.send(op='volume', guildId=self.guild_id, volume=self.volume)", "response": "Sets the player s volume."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nseeks to a given position in the track.", "response": "async def seek(self, pos: int):\r\n \"\"\" Seeks to a given position in the track. \"\"\"\r\n await self._lavalink.ws.send(op='seek', guildId=self.guild_id, position=pos)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\nasync def handle_event(self, event):\r\n if isinstance(event, (TrackStuckEvent, TrackExceptionEvent)) or \\\r\n isinstance(event, TrackEndEvent) and event.reason == 'FINISHED':\r\n await self.play()", "response": "Handles an event from the queue."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns a player object from the cache or creates one if it does not exist.", "response": "def get(self, guild_id):\r\n \"\"\" Returns a player from the cache, or creates one if it does not exist. \"\"\"\r\n if guild_id not in self._players:\r\n p = self._player(lavalink=self.lavalink, guild_id=guild_id)\r\n self._players[guild_id] = p\r\n\r\n return self._players[guild_id]"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nremove a player from the current players.", "response": "def remove(self, guild_id):\r\n \"\"\" Removes a player from the current players. \"\"\"\r\n if guild_id in self._players:\r\n self._players[guild_id].cleanup()\r\n del self._players[guild_id]"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nsearches and play a song from a given query.", "response": "async def _play(self, ctx, *, query: str):\r\n \"\"\" Searches and plays a song from a given query. \"\"\"\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n query = query.strip('<>')\r\n\r\n if not url_rx.match(query):\r\n query = f'ytsearch:{query}'\r\n\r\n tracks = await self.bot.lavalink.get_tracks(query)\r\n\r\n if not tracks:\r\n return await ctx.send('Nothing found!')\r\n\r\n embed = discord.Embed(color=discord.Color.blurple())\r\n\r\n if 'list' in query and 'ytsearch:' not in query:\r\n for track in tracks:\r\n player.add(requester=ctx.author.id, track=track)\r\n\r\n embed.title = 'Playlist enqueued!'\r\n embed.description = f'Imported {len(tracks)} tracks from the playlist!'\r\n await ctx.send(embed=embed)\r\n else:\r\n track_title = tracks[0][\"info\"][\"title\"]\r\n track_uri = tracks[0][\"info\"][\"uri\"]\r\n\r\n embed.title = \"Track enqueued!\"\r\n embed.description = f'[{track_title}]({track_uri})'\r\n player.add(requester=ctx.author.id, track=tracks[0])\r\n\r\n if not player.is_playing:\r\n await player.play()"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nseek to a given position in a track.", "response": "async def _seek(self, ctx, *, time: str):\r\n \"\"\" Seeks to a given position in a track. \"\"\"\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.is_playing:\r\n return await ctx.send('Not playing.')\r\n\r\n seconds = time_rx.search(time)\r\n if not seconds:\r\n return await ctx.send('You need to specify the amount of seconds to skip!')\r\n\r\n seconds = int(seconds.group()) * 1000\r\n if time.startswith('-'):\r\n seconds *= -1\r\n\r\n track_time = player.position + seconds\r\n await player.seek(track_time)\r\n\r\n await ctx.send(f'Moved track to **{lavalink.Utils.format_time(track_time)}**')"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nskip the current track.", "response": "async def _skip(self, ctx):\r\n \"\"\" Skips the current track. \"\"\"\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.is_playing:\r\n return await ctx.send('Not playing.')\r\n\r\n await player.skip()\r\n await ctx.send('\u23ed | Skipped.')"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\nasync def _stop(self, ctx):\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.is_playing:\r\n return await ctx.send('Not playing.')\r\n\r\n player.queue.clear()\r\n await player.stop()\r\n await ctx.send('\u23f9 | Stopped.')", "response": "Stops the player and clears its queue."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def _now(self, ctx):\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n song = 'Nothing'\r\n\r\n if player.current:\r\n position = lavalink.Utils.format_time(player.position)\r\n if player.current.stream:\r\n duration = '\ud83d\udd34 LIVE'\r\n else:\r\n duration = lavalink.Utils.format_time(player.current.duration)\r\n song = f'**[{player.current.title}]({player.current.uri})**\\n({position}/{duration})'\r\n\r\n embed = discord.Embed(color=discord.Color.blurple(), title='Now Playing', description=song)\r\n await ctx.send(embed=embed)", "response": "Show some stats about the currently playing song."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nshows the player s queue.", "response": "async def _queue(self, ctx, page: int = 1):\r\n \"\"\" Shows the player's queue. \"\"\"\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.queue:\r\n return await ctx.send('There\\'s nothing in the queue! Why not queue something?')\r\n\r\n items_per_page = 10\r\n pages = math.ceil(len(player.queue) / items_per_page)\r\n\r\n start = (page - 1) * items_per_page\r\n end = start + items_per_page\r\n\r\n queue_list = ''\r\n for index, track in enumerate(player.queue[start:end], start=start):\r\n queue_list += f'`{index + 1}.` [**{track.title}**]({track.uri})\\n'\r\n\r\n embed = discord.Embed(colour=discord.Color.blurple(),\r\n description=f'**{len(player.queue)} tracks**\\n\\n{queue_list}')\r\n embed.set_footer(text=f'Viewing page {page}/{pages}')\r\n await ctx.send(embed=embed)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\npause or resumes the current track.", "response": "async def _pause(self, ctx):\r\n \"\"\" Pauses/Resumes the current track. \"\"\"\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.is_playing:\r\n return await ctx.send('Not playing.')\r\n\r\n if player.paused:\r\n await player.set_pause(False)\r\n await ctx.send('\u23ef | Resumed')\r\n else:\r\n await player.set_pause(True)\r\n await ctx.send('\u23ef | Paused')"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def _volume(self, ctx, volume: int = None):\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not volume:\r\n return await ctx.send(f'\ud83d\udd08 | {player.volume}%')\r\n\r\n await player.set_volume(volume)\r\n await ctx.send(f'\ud83d\udd08 | Set to {player.volume}%')", "response": "Changes the player s volume."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\nasync def _shuffle(self, ctx):\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.is_playing:\r\n return await ctx.send('Nothing playing.')\r\n\r\n player.shuffle = not player.shuffle\r\n await ctx.send('\ud83d\udd00 | Shuffle ' + ('enabled' if player.shuffle else 'disabled'))", "response": "Shuffles the player's queue."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\nasync def _repeat(self, ctx):\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.is_playing:\r\n return await ctx.send('Nothing playing.')\r\n\r\n player.repeat = not player.repeat\r\n await ctx.send('\ud83d\udd01 | Repeat ' + ('enabled' if player.repeat else 'disabled'))", "response": "Repeats the current song until the command is invoked again."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\nasync def _remove(self, ctx, index: int):\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.queue:\r\n return await ctx.send('Nothing queued.')\r\n\r\n if index > len(player.queue) or index < 1:\r\n return await ctx.send(f'Index has to be **between** 1 and {len(player.queue)}')\r\n\r\n index -= 1\r\n removed = player.queue.pop(index)\r\n\r\n await ctx.send(f'Removed **{removed.title}** from the queue.')", "response": "Removes an item from the queue with the given index."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ndisconnect the player from the voice channel and clears its queue.", "response": "async def _disconnect(self, ctx):\r\n \"\"\" Disconnects the player from the voice channel and clears its queue. \"\"\"\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.is_connected:\r\n return await ctx.send('Not connected.')\r\n\r\n if not ctx.author.voice or (player.is_connected and ctx.author.voice.channel.id != int(player.channel_id)):\r\n return await ctx.send('You\\'re not in my voicechannel!')\r\n\r\n player.queue.clear()\r\n await player.disconnect()\r\n await ctx.send('*\u20e3 | Disconnected.')"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nensuring that the bot can join a voice channel.", "response": "async def ensure_voice(self, ctx):\r\n \"\"\" A few checks to make sure the bot can join a voice channel. \"\"\"\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.is_connected:\r\n if not ctx.author.voice or not ctx.author.voice.channel:\r\n await ctx.send('You aren\\'t connected to any voice channel.')\r\n raise commands.CommandInvokeError('Author not connected to voice channel.')\r\n\r\n permissions = ctx.author.voice.channel.permissions_for(ctx.me)\r\n\r\n if not permissions.connect or not permissions.speak:\r\n await ctx.send('Missing permissions `CONNECT` and/or `SPEAK`.')\r\n raise commands.CommandInvokeError('Bot has no permissions CONNECT and/or SPEAK')\r\n\r\n player.store('channel', ctx.channel.id)\r\n await player.connect(ctx.author.voice.channel.id)\r\n else:\r\n if player.connected_channel.id != ctx.author.voice.channel.id:\r\n return await ctx.send('Join my voice channel!')"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef register_hook(self, func):\r\n\r\n if func not in self.hooks:\r\n self.hooks.append(func)", "response": "Register a function as a hook."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef unregister_hook(self, func):\r\n if func in self.hooks:\r\n self.hooks.remove(func)", "response": "Unregisters a hook. For further explanation, please have a look at ``register_hook``."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\nasync def dispatch_event(self, event):\r\n log.debug('Dispatching event of type {} to {} hooks'.format(event.__class__.__name__, len(self.hooks)))\r\n for hook in self.hooks:\r\n try:\r\n if asyncio.iscoroutinefunction(hook):\r\n await hook(event)\r\n else:\r\n hook(event)\r\n except Exception as e: # pylint: disable=broad-except\r\n # Catch generic exception thrown by user hooks\r\n log.warning(\r\n 'Encountered exception while dispatching an event to hook `{}` ({})'.format(hook.__name__, str(e)))\r\n\r\n if isinstance(event, (TrackEndEvent, TrackExceptionEvent, TrackStuckEvent)) and event.player:\r\n await event.player.handle_event(event)", "response": "Dispatches an event to all registered hooks."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\nasync def update_state(self, data):\r\n guild_id = int(data['guildId'])\r\n\r\n if guild_id in self.players:\r\n player = self.players.get(guild_id)\r\n player.position = data['state'].get('position', 0)\r\n player.position_timestamp = data['state']['time']", "response": "Updates a player s state when a payload with opcode playerUpdate is received."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn a dictionary containing the tracks that match the given query.", "response": "async def get_tracks(self, query):\r\n \"\"\" Returns a Dictionary containing search results for a given query. \"\"\"\r\n log.debug('Requesting tracks for query {}'.format(query))\r\n\r\n async with self.http.get(self.rest_uri + quote(query), headers={'Authorization': self.password}) as res:\r\n return await res.json(content_type=None)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ndestroy the Lavalink client.", "response": "def destroy(self):\r\n \"\"\" Destroys the Lavalink client. \"\"\"\r\n self.ws.destroy()\r\n self.bot.remove_listener(self.on_socket_response)\r\n self.hooks.clear()"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef format_time(time):\r\n hours, remainder = divmod(time / 1000, 3600)\r\n minutes, seconds = divmod(remainder, 60)\r\n\r\n return '%02d:%02d:%02d' % (hours, minutes, seconds)", "response": "Formats the given time into HHMMSS format."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef build(self, track, requester):\r\n try:\r\n self.track = track['track']\r\n self.identifier = track['info']['identifier']\r\n self.can_seek = track['info']['isSeekable']\r\n self.author = track['info']['author']\r\n self.duration = track['info']['length']\r\n self.stream = track['info']['isStream']\r\n self.title = track['info']['title']\r\n self.uri = track['info']['uri']\r\n self.requester = requester\r\n\r\n return self\r\n except KeyError:\r\n raise InvalidTrack('An invalid track was passed.')", "response": "Builds an optional AudioTrack object from a dictionary."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\nasync def _previous(self, ctx):\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n try:\r\n await player.play_previous()\r\n except lavalink.NoPreviousTrack:\r\n await ctx.send('There is no previous song to play.')", "response": "Plays the previous song."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\nasync def _playnow(self, ctx, *, query: str):\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if not player.queue and not player.is_playing:\r\n return await ctx.invoke(self._play, query=query)\r\n\r\n query = query.strip('<>')\r\n\r\n if not url_rx.match(query):\r\n query = f'ytsearch:{query}'\r\n\r\n results = await self.bot.lavalink.get_tracks(query)\r\n\r\n if not results or not results['tracks']:\r\n return await ctx.send('Nothing found!')\r\n\r\n tracks = results['tracks']\r\n track = tracks.pop(0)\r\n\r\n if results['loadType'] == 'PLAYLIST_LOADED':\r\n for _track in tracks:\r\n player.add(requester=ctx.author.id, track=_track)\r\n\r\n await player.play_now(requester=ctx.author.id, track=track)", "response": "Plays immediately a song."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\nasync def _playat(self, ctx, index: int):\r\n player = self.bot.lavalink.players.get(ctx.guild.id)\r\n\r\n if index < 1:\r\n return await ctx.send('Invalid specified index.')\r\n\r\n if len(player.queue) < index:\r\n return await ctx.send('This index exceeds the queue\\'s length.')\r\n\r\n await player.play_at(index-1)", "response": "Plays the queue from a specific point. Disregards tracks before the index."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\nasync def _find(self, ctx, *, query):\r\n if not query.startswith('ytsearch:') and not query.startswith('scsearch:'):\r\n query = 'ytsearch:' + query\r\n\r\n results = await self.bot.lavalink.get_tracks(query)\r\n\r\n if not results or not results['tracks']:\r\n return await ctx.send('Nothing found')\r\n\r\n tracks = results['tracks'][:10] # First 10 results\r\n\r\n o = ''\r\n for index, track in enumerate(tracks, start=1):\r\n track_title = track[\"info\"][\"title\"]\r\n track_uri = track[\"info\"][\"uri\"]\r\n\r\n o += f'`{index}.` [{track_title}]({track_uri})\\n'\r\n\r\n embed = discord.Embed(color=discord.Color.blurple(), description=o)\r\n await ctx.send(embed=embed)", "response": "Find the first 10 results from a given query."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nadd suggestions to the AutoCompleter engine.", "response": "def add_suggestions(self, *suggestions, **kwargs):\n \"\"\"\n Add suggestion terms to the AutoCompleter engine. Each suggestion has a score and string.\n\n If kwargs['increment'] is true and the terms are already in the server's dictionary, we increment their scores\n \"\"\"\n pipe = self.redis.pipeline()\n for sug in suggestions:\n args = [AutoCompleter.SUGADD_COMMAND, self.key, sug.string, sug.score]\n if kwargs.get('increment'):\n args.append(AutoCompleter.INCR)\n if sug.payload:\n args.append('PAYLOAD')\n args.append(sug.payload)\n\n pipe.execute_command(*args)\n\n return pipe.execute()[-1]"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef delete(self, string):\n return self.redis.execute_command(AutoCompleter.SUGDEL_COMMAND, self.key, string)", "response": "Delete a string from the AutoCompleter index. Returns 0 if the string was not found and 1 otherwise."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef get_suggestions(self, prefix, fuzzy = False, num = 10, with_scores = False, with_payloads=False):\n\n args = [AutoCompleter.SUGGET_COMMAND, self.key, prefix, 'MAX', num]\n if fuzzy:\n args.append(AutoCompleter.FUZZY)\n if with_scores:\n args.append(AutoCompleter.WITHSCORES)\n if with_payloads:\n args.append(AutoCompleter.WITHPAYLOADS)\n\n ret = self.redis.execute_command(*args)\n results = []\n if not ret:\n return results\n\n parser = SuggestionParser(with_scores, with_payloads, ret)\n return [s for s in parser]", "response": "Get a list of suggestions for a given prefix."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ncreates the search index.", "response": "def create_index(self, fields, no_term_offsets=False,\n no_field_flags=False, stopwords = None):\n \"\"\"\n Create the search index. The index must not already exist.\n\n ### Parameters:\n\n - **fields**: a list of TextField or NumericField objects\n - **no_term_offsets**: If true, we will not save term offsets in the index\n - **no_field_flags**: If true, we will not save field flags that allow searching in specific fields\n - **stopwords**: If not None, we create the index with this custom stopword list. The list can be empty\n \"\"\"\n\n args = [self.CREATE_CMD, self.index_name]\n if no_term_offsets:\n args.append(self.NOOFFSETS)\n if no_field_flags:\n args.append(self.NOFIELDS)\n if stopwords is not None and isinstance(stopwords, (list, tuple, set)):\n args += [self.STOPWORDS, len(stopwords)]\n if len(stopwords) > 0:\n args += list(stopwords)\n \n args.append('SCHEMA')\n\n args += list(itertools.chain(*(f.redis_args() for f in fields)))\n\n return self.redis.execute_command(*args)"}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nadd a single document to the index.", "response": "def add_document(self, doc_id, nosave=False, score=1.0, payload=None,\n replace=False, partial=False, language=None, **fields):\n \"\"\"\n Add a single document to the index.\n\n ### Parameters\n\n - **doc_id**: the id of the saved document.\n - **nosave**: if set to true, we just index the document, and don't save a copy of it. This means that searches will just return ids.\n - **score**: the document ranking, between 0.0 and 1.0 \n - **payload**: optional inner-index payload we can save for fast access in scoring functions\n - **replace**: if True, and the document already is in the index, we perform an update and reindex the document\n - **partial**: if True, the fields specified will be added to the existing document.\n This has the added benefit that any fields specified with `no_index`\n will not be reindexed again. Implies `replace`\n - **language**: Specify the language used for document tokenization.\n - **fields** kwargs dictionary of the document fields to be saved and/or indexed. \n NOTE: Geo points shoule be encoded as strings of \"lon,lat\"\n \"\"\"\n return self._add_document(doc_id, conn=None, nosave=nosave, score=score, \n payload=payload, replace=replace,\n partial=partial, language=language, **fields)"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef delete_document(self, doc_id, conn=None):\n if conn is None:\n conn = self.redis\n\n return conn.execute_command(self.DEL_CMD, self.index_name, doc_id)", "response": "Delete a document from index."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef load_document(self, id):\n fields = self.redis.hgetall(id)\n if six.PY3:\n f2 = {to_string(k): to_string(v) for k, v in fields.items()}\n fields = f2\n\n try:\n del fields['id']\n except KeyError:\n pass\n\n return Document(id=id, **fields)", "response": "Load a single document by id"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngets info about the current index", "response": "def info(self):\n \"\"\"\n Get info an stats about the the current index, including the number of documents, memory consumption, etc\n \"\"\"\n\n res = self.redis.execute_command('FT.INFO', self.index_name)\n it = six.moves.map(to_string, res)\n return dict(six.moves.zip(it, it))"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nsearching the index for a given query and return a result of documents", "response": "def search(self, query):\n \"\"\"\n Search the index for a given query, and return a result of documents\n\n ### Parameters\n\n - **query**: the search query. Either a text for simple queries with default parameters, or a Query object for complex queries.\n See RediSearch's documentation on query format\n - **snippet_sizes**: A dictionary of {field: snippet_size} used to trim and format the result. e.g.e {'body': 500}\n \"\"\"\n args, query = self._mk_query_args(query)\n st = time.time()\n res = self.redis.execute_command(self.SEARCH_CMD, *args)\n\n return Result(res,\n not query._no_content,\n duration=(time.time() - st) * 1000.0,\n has_payload=query._with_payloads)"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef aggregate(self, query):\n if isinstance(query, AggregateRequest):\n has_schema = query._with_schema\n has_cursor = bool(query._cursor)\n cmd = [self.AGGREGATE_CMD, self.index_name] + query.build_args()\n elif isinstance(query, Cursor):\n has_schema = False\n has_cursor = True\n cmd = [self.CURSOR_CMD, 'READ', self.index_name] + query.build_args()\n else:\n raise ValueError('Bad query', query)\n\n raw = self.redis.execute_command(*cmd)\n if has_cursor:\n if isinstance(query, Cursor):\n query.cid = raw[1]\n cursor = query\n else:\n cursor = Cursor(raw[1])\n raw = raw[0]\n else:\n cursor = None\n\n if query._with_schema:\n schema = raw[0]\n rows = raw[2:]\n else:\n schema = None\n rows = raw[1:]\n\n res = AggregateResult(rows, cursor, schema)\n return res", "response": "Issue an aggregation query on the cache entry."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nsets the alias for this reducer.", "response": "def alias(self, alias):\n \"\"\"\n Set the alias for this reducer.\n\n ### Parameters\n\n - **alias**: The value of the alias for this reducer. If this is the\n special value `aggregation.FIELDNAME` then this reducer will be\n aliased using the same name as the field upon which it operates.\n Note that using `FIELDNAME` is only possible on reducers which\n operate on a single field value.\n\n This method returns the `Reducer` object making it suitable for\n chaining.\n \"\"\"\n if alias is FIELDNAME:\n if not self._field:\n raise ValueError(\"Cannot use FIELDNAME alias with no field\")\n # Chop off initial '@'\n alias = self._field[1:]\n self._alias = alias\n return self"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef group_by(self, fields, *reducers):\n group = Group(fields, reducers)\n self._groups.append(group)\n\n return self", "response": "Groups the entries in the log entry by the given fields."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef apply(self, **kwexpr):\n for alias, expr in kwexpr.items():\n self._projections.append([alias, expr])\n\n return self", "response": "Adds a projection expression to each result set."}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nsetting the limit for the most recent group or query.", "response": "def limit(self, offset, num):\n \"\"\"\n Sets the limit for the most recent group or query.\n\n If no group has been defined yet (via `group_by()`) then this sets\n the limit for the initial pool of results from the query. Otherwise,\n this limits the number of items operated on from the previous group.\n\n Setting a limit on the initial search results may be useful when\n attempting to execute an aggregation on a sample of a large data set.\n\n ### Parameters\n\n - **offset**: Result offset from which to begin paging\n - **num**: Number of results to return\n\n\n Example of sorting the initial results:\n\n ```\n AggregateRequest('@sale_amount:[10000, inf]')\\\n .limit(0, 10)\\\n .group_by('@state', r.count())\n ```\n\n Will only group by the states found in the first 10 results of the\n query `@sale_amount:[10000, inf]`. On the other hand,\n\n ```\n AggregateRequest('@sale_amount:[10000, inf]')\\\n .limit(0, 1000)\\\n .group_by('@state', r.count()\\\n .limit(0, 10)\n ```\n\n Will group all the results matching the query, but only return the\n first 10 groups.\n\n If you only wish to return a *top-N* style query, consider using\n `sort_by()` instead.\n\n \"\"\"\n limit = Limit(offset, num)\n if self._groups:\n self._groups[-1].limit = limit\n else:\n self._limit = limit\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef sort_by(self, *fields, **kwargs):\n self._max = kwargs.get('max', 0)\n if isinstance(fields, (string_types, SortDirection)):\n fields = [fields]\n for f in fields:\n if isinstance(f, SortDirection):\n self._sortby += [f.field, f.DIRSTRING]\n else:\n self._sortby.append(f)\n return self", "response": "Sort the list of items in the canoncache entry table."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef summarize(self, fields=None, context_len=None, num_frags=None, sep=None):\n args = ['SUMMARIZE']\n fields = self._mk_field_list(fields)\n if fields:\n args += ['FIELDS', str(len(fields))] + fields\n\n if context_len is not None:\n args += ['LEN', str(context_len)]\n if num_frags is not None:\n args += ['FRAGS', str(num_frags)]\n if sep is not None:\n args += ['SEPARATOR', sep]\n\n self._summarize_fields = args\n return self", "response": "Return an abridged format of the field containing only the segments of the document which contain the matching term s."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef highlight(self, fields=None, tags=None):\n args = ['HIGHLIGHT']\n fields = self._mk_field_list(fields)\n if fields:\n args += ['FIELDS', str(len(fields))] + fields\n if tags:\n args += ['TAGS'] + list(tags)\n\n self._highlight_fields = args\n return self", "response": "Highlights the matched term in the current instance."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_args(self):\n\n args = [self._query_string]\n\n if self._no_content:\n args.append('NOCONTENT')\n\n if self._fields:\n\n args.append('INFIELDS')\n args.append(len(self._fields))\n args += self._fields\n \n if self._verbatim:\n args.append('VERBATIM')\n\n if self._no_stopwords:\n args.append('NOSTOPWORDS')\n\n if self._filters:\n for flt in self._filters:\n assert isinstance(flt, Filter)\n args += flt.args\n\n if self._with_payloads:\n args.append('WITHPAYLOADS')\n \n if self._ids:\n args.append('INKEYS')\n args.append(len(self._ids))\n args += self._ids\n\n if self._slop >= 0:\n args += ['SLOP', self._slop]\n\n if self._in_order:\n args.append('INORDER')\n\n if self._return_fields:\n args.append('RETURN')\n args.append(len(self._return_fields))\n args += self._return_fields\n\n if self._sortby:\n assert isinstance(self._sortby, SortbyField)\n args.append('SORTBY')\n args += self._sortby.args\n\n if self._language:\n args += ['LANGUAGE', self._language]\n\n args += self._summarize_fields + self._highlight_fields\n args += [\"LIMIT\", self._offset, self._num]\n return args", "response": "Return the list of redis arguments for this query."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef paging(self, offset, num):\n self._offset = offset\n self._num = num\n return self", "response": "Sets the paging for the query."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nadds a sortby field to the query", "response": "def sort_by(self, field, asc=True):\n \"\"\"\n Add a sortby field to the query\n\n - **field** - the name of the field to sort by\n - **asc** - when `True`, sorting will be done in asceding order\n \"\"\"\n self._sortby = SortbyField(field, asc)\n return self"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef between(a, b, inclusive_min=True, inclusive_max=True):\n return RangeValue(a, b,\n inclusive_min=inclusive_min, inclusive_max=inclusive_max)", "response": "Returns a RangeValue object that is a numeric range between a and b."}
{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn a GeoValue object for the given latitude and longitude.", "response": "def geo(lat, lon, radius, unit='km'):\n \"\"\"\n Indicate that value is a geo region\n \"\"\"\n return GeoValue(lat, lon, radius, unit)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nbypass transformations. Parameters ---------- jam : pyjams.JAMS A muda-enabled JAMS object Yields ------ jam_out : pyjams.JAMS iterator The first result is `jam` (unmodified), by reference All subsequent results are generated by `transformer`", "response": "def transform(self, jam):\n '''Bypass transformations.\n\n Parameters\n ----------\n jam : pyjams.JAMS\n A muda-enabled JAMS object\n\n Yields\n ------\n jam_out : pyjams.JAMS iterator\n The first result is `jam` (unmodified), by reference\n All subsequent results are generated by `transformer`\n '''\n # Step 1: yield the unmodified jam\n yield jam\n\n # Step 2: yield from the transformer\n for jam_out in self.transformer.transform(jam):\n yield jam_out"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef __sox(y, sr, *args):\n '''Execute sox\n\n Parameters\n ----------\n y : np.ndarray\n Audio time series\n\n sr : int > 0\n Sampling rate of `y`\n\n *args\n Additional arguments to sox\n\n Returns\n -------\n y_out : np.ndarray\n `y` after sox transformation\n '''\n\n assert sr > 0\n\n fdesc, infile = tempfile.mkstemp(suffix='.wav')\n os.close(fdesc)\n fdesc, outfile = tempfile.mkstemp(suffix='.wav')\n os.close(fdesc)\n\n # Dump the audio\n librosa.output.write_wav(infile, y, sr)\n\n try:\n arguments = ['sox', infile, outfile, '-q']\n arguments.extend(args)\n\n subprocess.check_call(arguments)\n\n y_out, sr = psf.read(outfile)\n y_out = y_out.T\n if y.ndim == 1:\n y_out = librosa.to_mono(y_out)\n\n finally:\n os.unlink(infile)\n os.unlink(outfile)\n\n return y_out", "response": "Execute sox on the audio time series y and return the output of sox on the output."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef transpose(label, n_semitones):\n '''Transpose a chord label by some number of semitones\n\n Parameters\n ----------\n label : str\n A chord string\n\n n_semitones : float\n The number of semitones to move `label`\n\n Returns\n -------\n label_transpose : str\n The transposed chord label\n\n '''\n\n # Otherwise, split off the note from the modifier\n match = re.match(six.text_type('(?P[A-G][b#]*)(?P.*)'),\n six.text_type(label))\n\n if not match:\n return label\n\n note = match.group('note')\n\n new_note = librosa.midi_to_note(librosa.note_to_midi(note) + n_semitones,\n octave=False)\n\n return new_note + match.group('mod')", "response": "Transposes a chord label by some number of semitones."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\npack data into a jams sandbox.", "response": "def jam_pack(jam, **kwargs):\n '''Pack data into a jams sandbox.\n\n If not already present, this creates a `muda` field within `jam.sandbox`,\n along with `history`, `state`, and version arrays which are populated by\n deformation objects.\n\n Any additional fields can be added to the `muda` sandbox by supplying\n keyword arguments.\n\n Parameters\n ----------\n jam : jams.JAMS\n A JAMS object\n\n Returns\n -------\n jam : jams.JAMS\n The updated JAMS object\n\n Examples\n --------\n >>> jam = jams.JAMS()\n >>> muda.jam_pack(jam, my_data=dict(foo=5, bar=None))\n >>> jam.sandbox\n \n >>> jam.sandbox.muda\n \n >>> jam.sandbox.muda.my_data\n {'foo': 5, 'bar': None}\n '''\n\n if not hasattr(jam.sandbox, 'muda'):\n # If there's no mudabox, create one\n jam.sandbox.muda = jams.Sandbox(history=[],\n state=[],\n version=dict(muda=version,\n librosa=librosa.__version__,\n jams=jams.__version__,\n pysoundfile=psf.__version__))\n\n elif not isinstance(jam.sandbox.muda, jams.Sandbox):\n # If there is a muda entry, but it's not a sandbox, coerce it\n jam.sandbox.muda = jams.Sandbox(**jam.sandbox.muda)\n\n jam.sandbox.muda.update(**kwargs)\n\n return jam"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef load_jam_audio(jam_in, audio_file,\n validate=True,\n strict=True,\n fmt='auto',\n **kwargs):\n '''Load a jam and pack it with audio.\n\n Parameters\n ----------\n jam_in : str, file descriptor, or jams.JAMS\n JAMS filename, open file-descriptor, or object to load.\n See ``jams.load`` for acceptable formats.\n\n audio_file : str\n Audio filename to load\n\n validate : bool\n strict : bool\n fmt : str\n Parameters to `jams.load`\n\n kwargs : additional keyword arguments\n See `librosa.load`\n\n Returns\n -------\n jam : jams.JAMS\n A jams object with audio data in the top-level sandbox\n\n Notes\n -----\n This operation can modify the `file_metadata.duration` field of `jam_in`:\n If it is not currently set, it will be populated with the duration of the\n audio file.\n\n See Also\n --------\n jams.load\n librosa.core.load\n '''\n\n if isinstance(jam_in, jams.JAMS):\n jam = jam_in\n else:\n jam = jams.load(jam_in, validate=validate, strict=strict, fmt=fmt)\n\n y, sr = librosa.load(audio_file, **kwargs)\n\n if jam.file_metadata.duration is None:\n jam.file_metadata.duration = librosa.get_duration(y=y, sr=sr)\n\n return jam_pack(jam, _audio=dict(y=y, sr=sr))", "response": "Load a jam and pack it with audio."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef save(filename_audio, filename_jam, jam, strict=True, fmt='auto', **kwargs):\n '''Save a muda jam to disk\n\n Parameters\n ----------\n filename_audio: str\n The path to store the audio file\n\n filename_jam: str\n The path to store the jams object\n\n strict: bool\n Strict safety checking for jams output\n\n fmt : str\n Output format parameter for `jams.JAMS.save`\n\n kwargs\n Additional parameters to `soundfile.write`\n '''\n\n y = jam.sandbox.muda._audio['y']\n sr = jam.sandbox.muda._audio['sr']\n\n # First, dump the audio file\n psf.write(filename_audio, y, sr, **kwargs)\n\n # Then dump the jam\n jam.save(filename_jam, strict=strict, fmt=fmt)", "response": "Save a muda jam to disk"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef __reconstruct(params):\n '''Reconstruct a transformation or pipeline given a parameter dump.'''\n\n if isinstance(params, dict):\n if '__class__' in params:\n cls = params['__class__']\n data = __reconstruct(params['params'])\n return cls(**data)\n else:\n data = dict()\n for key, value in six.iteritems(params):\n data[key] = __reconstruct(value)\n return data\n\n elif isinstance(params, (list, tuple)):\n return [__reconstruct(v) for v in params]\n\n else:\n return params", "response": "Reconstruct a transformation or pipeline given a parameter dump."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef serialize(transform, **kwargs):\n '''Serialize a transformation object or pipeline.\n\n Parameters\n ----------\n transform : BaseTransform or Pipeline\n The transformation object to be serialized\n\n kwargs\n Additional keyword arguments to `jsonpickle.encode()`\n\n Returns\n -------\n json_str : str\n A JSON encoding of the transformation\n\n See Also\n --------\n deserialize\n\n Examples\n --------\n >>> D = muda.deformers.TimeStretch(rate=1.5)\n >>> muda.serialize(D)\n '{\"params\": {\"rate\": 1.5},\n \"__class__\": {\"py/type\": \"muda.deformers.time.TimeStretch\"}}'\n '''\n\n params = transform.get_params()\n return jsonpickle.encode(params, **kwargs)", "response": "Serialize a transformation object or pipeline."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nconstructs a muda transformation from a JSON encoded string.", "response": "def deserialize(encoded, **kwargs):\n '''Construct a muda transformation from a JSON encoded string.\n\n Parameters\n ----------\n encoded : str\n JSON encoding of the transformation or pipeline\n\n kwargs\n Additional keyword arguments to `jsonpickle.decode()`\n\n Returns\n -------\n obj\n The transformation\n\n See Also\n --------\n serialize\n\n Examples\n --------\n >>> D = muda.deformers.TimeStretch(rate=1.5)\n >>> D_serial = muda.serialize(D)\n >>> D2 = muda.deserialize(D_serial)\n >>> D2\n TimeStretch(rate=1.5)\n '''\n\n params = jsonpickle.decode(encoded, **kwargs)\n\n return __reconstruct(params)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting the list of parameter names for the object", "response": "def _get_param_names(cls):\n '''Get the list of parameter names for the object'''\n\n init = cls.__init__\n\n args, varargs = inspect.getargspec(init)[:2]\n\n if varargs is not None:\n raise RuntimeError('BaseTransformer objects cannot have varargs')\n\n args.pop(0)\n args.sort()\n return args"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns as a dict.", "response": "def get_params(self, deep=True):\n '''Get the parameters for this object. Returns as a dict.\n\n Parameters\n ----------\n deep : bool\n Recurse on nested objects\n\n Returns\n -------\n params : dict\n A dictionary containing all parameters for this object\n '''\n\n out = dict(__class__=self.__class__,\n params=dict())\n\n for key in self._get_param_names():\n value = getattr(self, key, None)\n\n if deep and hasattr(value, 'get_params'):\n deep_items = value.get_params().items()\n out['params'][key] = dict(__class__=value.__class__)\n out['params'][key].update((k, val) for k, val in deep_items)\n else:\n out['params'][key] = value\n\n return out"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\napply the transformation to audio and annotations.", "response": "def _transform(self, jam, state):\n '''Apply the transformation to audio and annotations.\n\n The input jam is copied and modified, and returned\n contained in a list.\n\n Parameters\n ----------\n jam : jams.JAMS\n A single jam object to modify\n\n Returns\n -------\n jam_list : list\n A length-1 list containing `jam` after transformation\n\n See also\n --------\n core.load_jam_audio\n '''\n\n if not hasattr(jam.sandbox, 'muda'):\n raise RuntimeError('No muda state found in jams sandbox.')\n\n # We'll need a working copy of this object for modification purposes\n jam_w = copy.deepcopy(jam)\n\n # Push our reconstructor onto the history stack\n jam_w.sandbox.muda['history'].append({'transformer': self.__serialize__,\n 'state': state})\n\n if hasattr(self, 'audio'):\n self.audio(jam_w.sandbox.muda, state)\n\n if hasattr(self, 'metadata'):\n self.metadata(jam_w.file_metadata, state)\n\n # Walk over the list of deformers\n for query, function_name in six.iteritems(self.dispatch):\n function = getattr(self, function_name)\n for matched_annotation in jam_w.search(namespace=query):\n function(matched_annotation, state)\n\n return jam_w"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns as a dict.", "response": "def get_params(self):\n '''Get the parameters for this object. Returns as a dict.'''\n\n out = {}\n out['__class__'] = self.__class__\n out['params'] = dict(steps=[])\n\n for name, step in self.steps:\n out['params']['steps'].append([name, step.get_params(deep=True)])\n\n return out"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\napplies the sequence of transformations to a single jam object.", "response": "def transform(self, jam):\n '''Apply the sequence of transformations to a single jam object.\n\n Parameters\n ----------\n jam : jams.JAMS\n The jam object to transform\n\n Yields\n ------\n jam_out : jams.JAMS\n The jam objects produced by the transformation sequence\n '''\n\n for output in self.__recursive_transform(jam, self.steps):\n yield output"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef transform(self, jam):\n '''Apply the sequence of transformations to a single jam object.\n\n Parameters\n ----------\n jam : jams.JAMS\n The jam object to transform\n\n Yields\n ------\n jam_out : jams.JAMS\n The jam objects produced by each member of the union\n '''\n\n for output in self.__serial_transform(jam, self.steps):\n yield output", "response": "Apply the sequence of transformations to a single jam object."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef sample_clip_indices(filename, n_samples, sr):\n '''Calculate the indices at which to sample a fragment of audio from a file.\n\n Parameters\n ----------\n filename : str\n Path to the input file\n\n n_samples : int > 0\n The number of samples to load\n\n sr : int > 0\n The target sampling rate\n\n Returns\n -------\n start : int\n The sample index from `filename` at which the audio fragment starts\n stop : int\n The sample index from `filename` at which the audio fragment stops (e.g. y = audio[start:stop])\n '''\n\n with psf.SoundFile(str(filename), mode='r') as soundf:\n # Measure required length of fragment\n n_target = int(np.ceil(n_samples * soundf.samplerate / float(sr)))\n\n # Raise exception if source is too short\n if len(soundf) < n_target:\n raise RuntimeError('Source {} (length={})'.format(filename, len(soundf)) +\n ' must be at least the length of the input ({})'.format(n_target))\n\n # Draw a starting point at random in the background waveform\n start = np.random.randint(0, 1 + len(soundf) - n_target)\n stop = start + n_target\n\n return start, stop", "response": "Calculate the indices at which to sample a fragment of audio from a file."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef slice_clip(filename, start, stop, n_samples, sr, mono=True):\n '''Slice a fragment of audio from a file.\n\n This uses pysoundfile to efficiently seek without\n loading the entire stream.\n\n Parameters\n ----------\n filename : str\n Path to the input file\n\n start : int\n The sample index of `filename` at which the audio fragment should start\n\n stop : int\n The sample index of `filename` at which the audio fragment should stop (e.g. y = audio[start:stop])\n\n n_samples : int > 0\n The number of samples to load\n\n sr : int > 0\n The target sampling rate\n\n mono : bool\n Ensure monophonic audio\n\n Returns\n -------\n y : np.ndarray [shape=(n_samples,)]\n A fragment of audio sampled from `filename`\n\n Raises\n ------\n ValueError\n If the source file is shorter than the requested length\n\n '''\n\n with psf.SoundFile(str(filename), mode='r') as soundf:\n n_target = stop - start\n\n soundf.seek(start)\n\n y = soundf.read(n_target).T\n\n if mono:\n y = librosa.to_mono(y)\n\n # Resample to initial sr\n y = librosa.resample(y, soundf.samplerate, sr)\n\n # Clip to the target length exactly\n y = librosa.util.fix_length(y, n_samples)\n\n return y", "response": "Slice a fragment of audio from a file."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nnormalizing `path`. All remote paths are absolute.", "response": "def norm_remote_path(path):\n \"\"\"Normalize `path`.\n\n All remote paths are absolute.\n \"\"\"\n path = os.path.normpath(path)\n if path.startswith(os.path.sep):\n return path[1:]\n else:\n return path"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef split_storage(path, default='osfstorage'):\n path = norm_remote_path(path)\n\n for provider in KNOWN_PROVIDERS:\n if path.startswith(provider + '/'):\n if six.PY3:\n return path.split('/', maxsplit=1)\n else:\n return path.split('/', 1)\n\n return (default, path)", "response": "Extract storage name from a file path."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\ndetermine if a file is empty or not.", "response": "def file_empty(fp):\n \"\"\"Determine if a file is empty or not.\"\"\"\n # for python 2 we need to use a homemade peek()\n if six.PY2:\n contents = fp.read()\n fp.seek(0)\n return not bool(contents)\n\n else:\n return not fp.peek()"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef checksum(file_path, hash_type='md5', block_size=65536):\n if hash_type == 'md5':\n hash_ = hashlib.md5()\n elif hash_type == 'sha256':\n hash_ = hashlib.sha256()\n else:\n raise ValueError(\n \"{} is an invalid hash_type. Expected 'md5' or 'sha256'.\"\n .format(hash_type)\n )\n\n with open(file_path, 'rb') as f:\n for block in iter(lambda: f.read(block_size), b''):\n hash_.update(block)\n return hash_.hexdigest()", "response": "Returns either the md5 or sha256 hash of a file at file_path."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef storages(self):\n stores = self._json(self._get(self._storages_url), 200)\n stores = stores['data']\n for store in stores:\n yield Storage(store, self.session)", "response": "Iterate over all storages for this projects."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ncreate a new file at path in this storage.", "response": "def create_file(self, path, fp, force=False, update=False):\n \"\"\"Store a new file at `path` in this storage.\n\n The contents of the file descriptor `fp` (opened in 'rb' mode)\n will be uploaded to `path` which is the full path at\n which to store the file.\n\n To force overwrite of an existing file, set `force=True`.\n To overwrite an existing file only if the files differ, set `update=True`\n \"\"\"\n if 'b' not in fp.mode:\n raise ValueError(\"File has to be opened in binary mode.\")\n\n # all paths are assumed to be absolute\n path = norm_remote_path(path)\n\n directory, fname = os.path.split(path)\n directories = directory.split(os.path.sep)\n # navigate to the right parent object for our file\n parent = self\n for directory in directories:\n # skip empty directory names\n if directory:\n parent = parent.create_folder(directory, exist_ok=True)\n\n url = parent._new_file_url\n\n # When uploading a large file (>a few MB) that already exists\n # we sometimes get a ConnectionError instead of a status == 409.\n connection_error = False\n \n # peek at the file to check if it is an empty file which needs special\n # handling in requests. If we pass a file like object to data that\n # turns out to be of length zero then no file is created on the OSF.\n # See: https://github.com/osfclient/osfclient/pull/135\n if file_empty(fp):\n response = self._put(url, params={'name': fname}, data=b'')\n else:\n try:\n response = self._put(url, params={'name': fname}, data=fp)\n except ConnectionError:\n connection_error = True\n\n if connection_error or response.status_code == 409:\n if not force and not update:\n # one-liner to get file size from file pointer from\n # https://stackoverflow.com/a/283719/2680824\n file_size_bytes = get_local_file_size(fp)\n large_file_cutoff = 2**20 # 1 MB in bytes\n if connection_error and file_size_bytes < large_file_cutoff:\n msg = (\n \"There was a connection error which might mean {} \" +\n \"already exists. Try again with the `--force` flag \" +\n \"specified.\"\n ).format(path)\n raise RuntimeError(msg)\n else:\n # note in case of connection error, we are making an inference here\n raise FileExistsError(path)\n\n else:\n # find the upload URL for the file we are trying to update\n for file_ in self.files:\n if norm_remote_path(file_.path) == path:\n if not force:\n if checksum(path) == file_.hashes.get('md5'):\n # If the hashes are equal and force is False,\n # we're done here\n break\n # in the process of attempting to upload the file we\n # moved through it -> reset read position to beginning\n # of the file\n fp.seek(0)\n file_.update(fp)\n break\n else:\n raise RuntimeError(\"Could not create a new file at \"\n \"({}) nor update it.\".format(path))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ncopying data from file - like object fsrc to file - like object fdst", "response": "def copyfileobj(fsrc, fdst, total, length=16*1024):\n \"\"\"Copy data from file-like object fsrc to file-like object fdst\n\n This is like shutil.copyfileobj but with a progressbar.\n \"\"\"\n with tqdm(unit='bytes', total=total, unit_scale=True) as pbar:\n while 1:\n buf = fsrc.read(length)\n if not buf:\n break\n fdst.write(buf)\n pbar.update(len(buf))"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nwrites contents of this file to a local file.", "response": "def write_to(self, fp):\n \"\"\"Write contents of this file to a local file.\n\n Pass in a filepointer `fp` that has been opened for writing in\n binary mode.\n \"\"\"\n if 'b' not in fp.mode:\n raise ValueError(\"File has to be opened in binary mode.\")\n\n response = self._get(self._download_url, stream=True)\n if response.status_code == 200:\n response.raw.decode_content = True\n copyfileobj(response.raw, fp,\n int(response.headers['Content-Length']))\n\n else:\n raise RuntimeError(\"Response has status \"\n \"code {}.\".format(response.status_code))"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef remove(self):\n response = self._delete(self._delete_url)\n if response.status_code != 204:\n raise RuntimeError('Could not delete {}.'.format(self.path))", "response": "Remove this file from the remote storage."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef update(self, fp):\n if 'b' not in fp.mode:\n raise ValueError(\"File has to be opened in binary mode.\")\n\n url = self._upload_url\n # peek at the file to check if it is an ampty file which needs special\n # handling in requests. If we pass a file like object to data that\n # turns out to be of length zero then no file is created on the OSF\n if fp.peek(1):\n response = self._put(url, data=fp)\n else:\n response = self._put(url, data=b'')\n\n if response.status_code != 200:\n msg = ('Could not update {} (status '\n 'code: {}).'.format(self.path, response.status_code))\n raise RuntimeError(msg)", "response": "Update the remote file from a local file pointer."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _iter_children(self, url, kind, klass, recurse=None):\n children = self._follow_next(url)\n\n while children:\n child = children.pop()\n kind_ = child['attributes']['kind']\n if kind_ == kind:\n yield klass(child, self.session)\n elif recurse is not None:\n # recurse into a child and add entries to `children`\n url = self._get_attribute(child, *recurse)\n children.extend(self._follow_next(url))", "response": "Iterate over all children of kind and yield klass when a child is of type kind."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ndecorating a CLI function that might require authentication.", "response": "def might_need_auth(f):\n \"\"\"Decorate a CLI function that might require authentication.\n\n Catches any UnauthorizedException raised, prints a helpful message and\n then exits.\n \"\"\"\n @wraps(f)\n def wrapper(cli_args):\n try:\n return_value = f(cli_args)\n except UnauthorizedException as e:\n config = config_from_env(config_from_file())\n username = _get_username(cli_args, config)\n\n if username is None:\n sys.exit(\"Please set a username (run `osf -h` for details).\")\n else:\n sys.exit(\"You are not authorized to access this project.\")\n\n return return_value\n\n return wrapper"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef init(args):\n # reading existing config file, convert to configparser object\n config = config_from_file()\n config_ = configparser.ConfigParser()\n config_.add_section('osf')\n if 'username' not in config.keys():\n config_.set('osf', 'username', '')\n else:\n config_.set('osf', 'username', config['username'])\n if 'project' not in config.keys():\n config_.set('osf', 'project', '')\n else:\n config_.set('osf', 'project', config['project'])\n\n # now we can start asking for new values\n print('Provide a username for the config file [current username: {}]:'.format(\n config_.get('osf', 'username')))\n username = input()\n if username:\n config_.set('osf', 'username', username)\n\n print('Provide a project for the config file [current project: {}]:'.format(\n config_.get('osf', 'project')))\n project = input()\n if project:\n config_.set('osf', 'project', project)\n\n cfgfile = open(\".osfcli.config\", \"w\")\n config_.write(cfgfile)\n cfgfile.close()", "response": "Initialize or edit an existing. osfcli. config file."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef clone(args):\n osf = _setup_osf(args)\n project = osf.project(args.project)\n output_dir = args.project\n if args.output is not None:\n output_dir = args.output\n\n with tqdm(unit='files') as pbar:\n for store in project.storages:\n prefix = os.path.join(output_dir, store.name)\n\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n\n path = os.path.join(prefix, path)\n if os.path.exists(path) and args.update:\n if checksum(path) == file_.hashes.get('md5'):\n continue\n directory, _ = os.path.split(path)\n makedirs(directory, exist_ok=True)\n\n with open(path, \"wb\") as f:\n file_.write_to(f)\n\n pbar.update()", "response": "Copy all files from all storages of a project to the output directory."}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nfetches an individual file from a project.", "response": "def fetch(args):\n \"\"\"Fetch an individual file from a project.\n\n The first part of the remote path is interpreted as the name of the\n storage provider. If there is no match the default (osfstorage) is\n used.\n\n The local path defaults to the name of the remote file.\n\n If the project is private you need to specify a username.\n\n If args.force is True, write local file even if that file already exists.\n If args.force is False but args.update is True, overwrite an existing local\n file only if local and remote files differ.\n \"\"\"\n storage, remote_path = split_storage(args.remote)\n\n local_path = args.local\n if local_path is None:\n _, local_path = os.path.split(remote_path)\n\n local_path_exists = os.path.exists(local_path)\n if local_path_exists and not args.force and not args.update:\n sys.exit(\"Local file %s already exists, not overwriting.\" % local_path)\n\n directory, _ = os.path.split(local_path)\n if directory:\n makedirs(directory, exist_ok=True)\n\n osf = _setup_osf(args)\n project = osf.project(args.project)\n\n store = project.storage(storage)\n for file_ in store.files:\n if norm_remote_path(file_.path) == remote_path:\n if local_path_exists and not args.force and args.update:\n if file_.hashes.get('md5') == checksum(local_path):\n print(\"Local file %s already matches remote.\" % local_path)\n break\n with open(local_path, 'wb') as fp:\n file_.write_to(fp)\n\n # only fetching one file so we are done\n break"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nlist all files from all storages for the project.", "response": "def list_(args):\n \"\"\"List all files from all storages for project.\n\n If the project is private you need to specify a username.\n \"\"\"\n osf = _setup_osf(args)\n\n project = osf.project(args.project)\n\n for store in project.storages:\n prefix = store.name\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n\n print(os.path.join(prefix, path))"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef upload(args):\n osf = _setup_osf(args)\n if osf.username is None or osf.password is None:\n sys.exit('To upload a file you need to provide a username and'\n ' password.')\n\n project = osf.project(args.project)\n storage, remote_path = split_storage(args.destination)\n\n store = project.storage(storage)\n if args.recursive:\n if not os.path.isdir(args.source):\n raise RuntimeError(\"Expected source ({}) to be a directory when \"\n \"using recursive mode.\".format(args.source))\n\n # local name of the directory that is being uploaded\n _, dir_name = os.path.split(args.source)\n\n for root, _, files in os.walk(args.source):\n subdir_path = os.path.relpath(root, args.source)\n for fname in files:\n local_path = os.path.join(root, fname)\n with open(local_path, 'rb') as fp:\n # build the remote path + fname\n name = os.path.join(remote_path, dir_name, subdir_path,\n fname)\n store.create_file(name, fp, force=args.force,\n update=args.update)\n\n else:\n with open(args.source, 'rb') as fp:\n store.create_file(remote_path, fp, force=args.force,\n update=args.update)", "response": "Upload a new file to an existing project."}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef remove(args):\n osf = _setup_osf(args)\n if osf.username is None or osf.password is None:\n sys.exit('To remove a file you need to provide a username and'\n ' password.')\n\n project = osf.project(args.project)\n\n storage, remote_path = split_storage(args.target)\n\n store = project.storage(storage)\n for f in store.files:\n if norm_remote_path(f.path) == remote_path:\n f.remove()", "response": "Remove a file from the project s storage."}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef login(self, username, password=None, token=None):\n self.session.basic_auth(username, password)", "response": "Login user for protected API calls."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ndetermining the JSONAPI type for a given GUID", "response": "def guid(self, guid):\n \"\"\"Determines JSONAPI type for provided GUID\"\"\"\n return self._json(self._get(self._build_url('guids', guid)), 200)['data']['type']"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nextracting JSON from response if status_code matches.", "response": "def _json(self, response, status_code):\n \"\"\"Extract JSON from response if `status_code` matches.\"\"\"\n if isinstance(status_code, numbers.Integral):\n status_code = (status_code,)\n\n if response.status_code in status_code:\n return response.json()\n else:\n raise RuntimeError(\"Response has status \"\n \"code {} not {}\".format(response.status_code,\n status_code))"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nfollow the next link on paginated results.", "response": "def _follow_next(self, url):\n \"\"\"Follow the 'next' link on paginated results.\"\"\"\n response = self._json(self._get(url), 200)\n data = response['data']\n\n next_url = self._get_attribute(response, 'links', 'next')\n while next_url is not None:\n response = self._json(self._get(next_url), 200)\n data.extend(response['data'])\n next_url = self._get_attribute(response, 'links', 'next')\n\n return data"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ncreating a new project using recursion and alias resolution.", "response": "def project(*descs, root_file=None):\n \"\"\"\n Make a new project, using recursion and alias resolution.\n\n Use this function in preference to calling Project() directly.\n \"\"\"\n load.ROOT_FILE = root_file\n\n desc = merge.merge(merge.DEFAULT_PROJECT, *descs)\n path = desc.get('path', '')\n\n if root_file:\n project_path = os.path.dirname(root_file)\n if path:\n path += ':' + project_path\n else:\n path = project_path\n\n with load.extender(path):\n desc = recurse.recurse(desc)\n\n project = construct.construct(**desc)\n project.desc = desc\n return project"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nclearing description to default values", "response": "def clear(self):\n \"\"\"Clear description to default values\"\"\"\n self._desc = {}\n for key, value in merge.DEFAULT_PROJECT.items():\n if key not in self._HIDDEN:\n self._desc[key] = type(value)()"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef update(self, desc=None, **kwds):\n sections.update(self._desc, desc, **kwds)", "response": "Update the internal dictionary with the given description."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nwraps function for SPI device drivers on systems like theSPIRaspberry Pi and BeagleBone.", "response": "def SPI(ledtype=None, num=0, **kwargs):\n \"\"\"Wrapper function for using SPI device drivers on systems like the\n Raspberry Pi and BeagleBone. This allows using any of the SPI drivers\n from a single entry point instead importing the driver for a specific\n LED type.\n\n Provides the same parameters of\n :py:class:`bibliopixel.drivers.SPI.SPIBase` as\n well as those below:\n\n :param ledtype: One of: LPD8806, WS2801, WS281X, or APA102\n \"\"\"\n\n from ...project.types.ledtype import make\n if ledtype is None:\n raise ValueError('Must provide ledtype value!')\n ledtype = make(ledtype)\n\n if num == 0:\n raise ValueError('Must provide num value >0!')\n if ledtype not in SPI_DRIVERS.keys():\n raise ValueError('{} is not a valid LED type.'.format(ledtype))\n\n return SPI_DRIVERS[ledtype](num, **kwargs)"}
{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef put_edit(self, f, *args, **kwds):\n self.put_nowait(functools.partial(f, *args, **kwds))", "response": "Defer an edit to run on the EditQueue."}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nget all the edits in the queue and execute them.", "response": "def get_and_run_edits(self):\n \"\"\"\n Get all the edits in the queue, then execute them.\n\n The algorithm gets all edits, and then executes all of them. It does\n *not* pull off one edit, execute, repeat until the queue is empty, and\n that means that the queue might not be empty at the end of\n ``run_edits``, because new edits might have entered the queue\n while the previous edits are being executed.\n\n This has the advantage that if edits enter the queue faster than they\n can be processed, ``get_and_run_edits`` won't go into an infinite loop,\n but rather the queue will grow unboundedly, which that can be\n detected, and mitigated and reported on - or if Queue.maxsize is\n set, ``bp`` will report a fairly clear error and just dump the edits\n on the ground.\n \"\"\"\n if self.empty():\n return\n\n edits = []\n while True:\n try:\n edits.append(self.get_nowait())\n except queue.Empty:\n break\n\n for e in edits:\n try:\n e()\n except:\n log.error('Error on edit %s', e)\n traceback.print_exc()"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef error(self, text):\n msg = 'Error with dev: {}, spi_speed: {} - {}'.format(\n self._dev, self._spi_speed, text)\n log.error(msg)\n raise IOError(msg)", "response": "Raise IOError if the error occured."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nsend packet to the SPI bus.", "response": "def send_packet(self, data):\n \"\"\"SHOULD BE PRIVATE\"\"\"\n package_size = 4032 # bit smaller than 4096 because of headers\n for i in range(int(math.ceil(len(data) / package_size))):\n start = i * package_size\n end = (i + 1) * package_size\n self._spi.write(data[start:end])\n self._spi.flush()"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef find_serial_devices(self):\n if self.devices is not None:\n return self.devices\n\n self.devices = {}\n hardware_id = \"(?i)\" + self.hardware_id # forces case insensitive\n\n for ports in serial.tools.list_ports.grep(hardware_id):\n port = ports[0]\n try:\n id = self.get_device_id(port)\n ver = self._get_device_version(port)\n except:\n log.debug('Error getting device_id for %s, %s',\n port, self.baudrate)\n if True:\n raise\n continue\n\n if getattr(ports, '__len__', lambda: 0)():\n log.debug('Multi-port device %s:%s:%s with %s ports found',\n self.hardware_id, id, ver, len(ports))\n if id < 0:\n log.debug('Serial device %s:%s:%s with id %s < 0',\n self.hardware_id, id, ver)\n else:\n self.devices[id] = port, ver\n\n return self.devices", "response": "Scan and report all compatible serial devices on system."}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef get_device(self, id=None):\n if id is None:\n if not self.devices:\n raise ValueError('No default device for %s' % self.hardware_id)\n id, (device, version) = sorted(self.devices.items())[0]\n\n elif id in self.devices:\n device, version = self.devices[id]\n\n else:\n error = 'Unable to find device with ID %s' % id\n log.error(error)\n raise ValueError(error)\n\n log.info(\"Using COM Port: %s, Device ID: %s, Device Ver: %s\",\n device, id, version)\n return id, device, version", "response": "Returns details of the first or specified device."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef error(self, fail=True, action=''):\n e = 'There was an unknown error communicating with the device.'\n if action:\n e = 'While %s: %s' % (action, e)\n log.error(e)\n if fail:\n raise IOError(e)", "response": "This method is used to log an error message when the device is not available."}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nsets the ID of the current device.", "response": "def set_device_id(self, dev, id):\n \"\"\"Set device ID to new value.\n\n :param str dev: Serial device address/path\n :param id: Device ID to set\n \"\"\"\n if id < 0 or id > 255:\n raise ValueError(\"ID must be an unsigned byte!\")\n com, code, ok = io.send_packet(\n CMDTYPE.SETID, 1, dev, self.baudrate, 5, id)\n if not ok:\n raise_error(code)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef get_device_id(self, dev):\n com, code, ok = io.send_packet(CMDTYPE.GETID, 0, dev, self.baudrate, 5)\n if code is None:\n self.error(action='get_device_id')\n return code", "response": "Get the ID at given device address and path."}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngets a named palette or None if no such palette exists.", "response": "def get(name=None):\n \"\"\"\n Return a named Palette, or None if no such name exists.\n\n If ``name`` is omitted, the default value is used.\n \"\"\"\n if name is None or name == 'default':\n return _DEFAULT_PALETTE\n\n if isinstance(name, str):\n return PROJECT_PALETTES.get(name) or BUILT_IN_PALETTES.get(name)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns an image cropped on top bottom left or right.", "response": "def crop(image, top_offset=0, left_offset=0, bottom_offset=0, right_offset=0):\n \"\"\"Return an image cropped on top, bottom, left or right.\"\"\"\n if bottom_offset or top_offset or left_offset or right_offset:\n width, height = image.size\n box = (left_offset, top_offset,\n width - right_offset, height - bottom_offset)\n image = image.crop(box=box)\n\n return image"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn an image resized.", "response": "def resize(image, x, y, stretch=False, top=None, left=None, mode='RGB',\n resample=None):\n \"\"\"Return an image resized.\"\"\"\n if x <= 0:\n raise ValueError('x must be greater than zero')\n if y <= 0:\n raise ValueError('y must be greater than zero')\n\n from PIL import Image\n\n resample = Image.ANTIALIAS if resample is None else resample\n if not isinstance(resample, numbers.Number):\n try:\n resample = getattr(Image, resample.upper())\n except:\n raise ValueError(\"(1) Didn't understand resample=%s\" % resample)\n if not isinstance(resample, numbers.Number):\n raise ValueError(\"(2) Didn't understand resample=%s\" % resample)\n\n size = x, y\n if stretch:\n return image.resize(size, resample=resample)\n result = Image.new(mode, size)\n\n ratios = [d1 / d2 for d1, d2 in zip(size, image.size)]\n if ratios[0] < ratios[1]:\n new_size = (size[0], int(image.size[1] * ratios[0]))\n else:\n new_size = (int(image.size[0] * ratios[1]), size[1])\n\n image = image.resize(new_size, resample=resample)\n if left is None:\n box_x = int((x - new_size[0]) / 2)\n elif left:\n box_x = 0\n else:\n box_x = x - new_size[0]\n\n if top is None:\n box_y = int((y - new_size[1]) / 2)\n elif top:\n box_y = 0\n else:\n box_y = y - new_size[1]\n\n result.paste(image, box=(box_x, box_y))\n return result"}
{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef extract(self, msg):\n def normal(key):\n v = msg.get(key)\n if v is None:\n return v\n normalizer = self.normalizers.get(key, lambda x: x)\n return normalizer(v)\n\n def odict(keys):\n return collections.OrderedDict((k, normal(k)) for k in keys)\n\n def match(m):\n return (msg.get(k) in v for k, v in m.items()) if m else ()\n\n accept = all(match(self.accept))\n reject = any(match(self.reject))\n\n if reject or not accept:\n keys = ()\n elif self.keys_by_type is None:\n keys = [k for k in msg.keys() if k not in self.omit]\n else:\n keys = self.keys_by_type.get(msg.get('type'))\n return odict(keys)", "response": "Yield an ordered dictionary if msg has a type in keys_by_type."}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef get(self, x, y):\n try:\n pixel = self.coord_map[y][x]\n return self._get_base(pixel)\n except IndexError:\n return colors.COLORS.Black", "response": "Return the color at the given position."}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef drawCircle(self, x0, y0, r, color=None):\n md.draw_circle(self.set, x0, y0, r, color)", "response": "Draw a circle in an RGB color with center x0 y0 r"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef fillCircle(self, x0, y0, r, color=None):\n md.fill_circle(self.set, x0, y0, r, color)", "response": "Draw a filled circle in an RGB color with center x0 y0 r"}
{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef drawLine(self, x0, y0, x1, y1, color=None, colorFunc=None, aa=False):\n md.draw_line(self.set, x0, y0, x1, y1, color, colorFunc, aa)", "response": "Draw a line between x0 y0 and x1 y1 in an RGB color."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ndrawing a line from point x0 y0 to x1 y1 using Bresenham s algorithm.", "response": "def bresenham_line(self, x0, y0, x1, y1, color=None, colorFunc=None):\n \"\"\"\n Draw line from point x0, y0 to x1, y1 using Bresenham's algorithm.\n\n Will draw beyond matrix bounds.\n \"\"\"\n md.bresenham_line(self.set, x0, y0, x1, y1, color, colorFunc)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ndraw rectangle with top - left corner at x y width w and height h", "response": "def drawRect(self, x, y, w, h, color=None, aa=False):\n \"\"\"\n Draw rectangle with top-left corner at x,y, width w and height h\n\n :param aa: if True, use Bresenham's algorithm for line drawing;\n otherwise use Xiaolin Wu's algorithm\n \"\"\"\n md.draw_rect(self.set, x, y, w, h, color, aa)"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nfill the matrix with the given RGB color", "response": "def fillScreen(self, color=None):\n \"\"\"Fill the matrix with the given RGB color\"\"\"\n md.fill_rect(self.set, 0, 0, self.width, self.height, color)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef drawRoundRect(self, x, y, w, h, r, color=None, aa=False):\n md.draw_round_rect(self.set, x, y, w, h, r, color, aa)", "response": "Draw a rounded rectangle with top - left corner at x y w h and corner radius r"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef fillRoundRect(self, x, y, w, h, r, color=None, aa=False):\n md.fill_round_rect(self.set, x, y, w, h, r, color, aa)", "response": "Draw a rounded rectangle with top - left corner at ( x y w h and corner radius r"}
{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef drawTriangle(self, x0, y0, x1, y1, x2, y2, color=None, aa=False):\n md.draw_triangle(self.set, x0, y0, x1, y1, x2, y2, color, aa)", "response": "Draw a triangle with vertices x0 y0 x1 y1 x2 y2 color aa"}
{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ndraws filled triangle with points x0 y0 x1 y1 x2 y2 color aa", "response": "def fillTriangle(self, x0, y0, x1, y1, x2, y2, color=None, aa=False):\n \"\"\"\n Draw filled triangle with points x0,y0 - x1,y1 - x2,y2\n\n :param aa: if True, use Bresenham's algorithm for line drawing;\n otherwise use Xiaolin Wu's algorithm\n \"\"\"\n md.fill_triangle(self.set, x0, y0, x1, y1, x2, y2, color, aa)"}
{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef drawChar(self, x, y, c, color, bg,\n aa=False, font=font.default_font, font_scale=1):\n \"\"\"\n Draw a single character c at at (x, y) in an RGB color.\n \"\"\"\n md.draw_char(self.fonts, self.set, self.width, self.height,\n x, y, c, color, bg, aa, font, font_scale)", "response": "Draw a single character at the specified location."}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ndrawing a line of text starting at x y in color.", "response": "def drawText(self, text, x=0, y=0, color=None,\n bg=colors.COLORS.Off, aa=False, font=font.default_font,\n font_scale=1):\n \"\"\"\n Draw a line of text starting at (x, y) in an RGB color.\n\n :param colorFunc: a function that takes an integer from x0 to x1 and\n returns a color corresponding to that point\n :param aa: if True, use Bresenham's algorithm for line drawing;\n otherwise use Xiaolin Wu's algorithm\n \"\"\"\n md.draw_text(self.fonts, self.set, text, self.width, self.height,\n x, y, color, bg, aa, font, font_scale)"}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nsets the base project for routing.", "response": "def set_project(self, project):\n \"\"\"Set the base project for routing.\"\"\"\n def visit(x):\n # Try to set_project, then recurse through any values()\n set_project = getattr(x, 'set_project', None)\n if set_project:\n set_project(project)\n values = getattr(x, 'values', lambda: ())\n for v in values():\n visit(v)\n\n visit(self.routing)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning a tuple where receiver is the object with a receive method that can accept that message.", "response": "def receive(self, msg):\n \"\"\"\n Returns a (receiver, msg) pair, where receiver is `None` if no route for\n the message was found, or otherwise an object with a `receive` method\n that can accept that `msg`.\n \"\"\"\n x = self.routing\n while not isinstance(x, ActionList):\n if not x or not msg:\n return None, msg\n\n if not isinstance(x, dict):\n raise ValueError('Unexpected type %s' % type(x))\n\n _, value = msg.popitem(last=False)\n x = x.get(str(value))\n\n return x, msg"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nsetting pixel to RGB color tuple", "response": "def set(self, ring, angle, color):\n \"\"\"Set pixel to RGB color tuple\"\"\"\n pixel = self.angleToPixel(angle, ring)\n self._set_base(pixel, color)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\ngetting RGB color tuple of color at index pixel", "response": "def get(self, ring, angle):\n \"\"\"Get RGB color tuple of color at index pixel\"\"\"\n pixel = self.angleToPixel(angle, ring)\n return self._get_base(pixel)"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef run(function, *args, use_subprocess=False, daemon=True, **kwds):\n if use_subprocess:\n Creator, Queue = multiprocessing.Process, multiprocessing.Queue\n else:\n Creator, Queue = threading.Thread, queue.Queue\n\n input, output = Queue(), Queue()\n args = input, output, function, args\n sub = Creator(target=_run_locally, args=args, kwargs=kwds, daemon=daemon)\n sub.start()\n\n return sub, input, output", "response": "Run a function in a new process or thread."}
{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef color_scale(color, level):\n return tuple([int(i * level) >> 8 for i in list(color)])", "response": "Scale RGB tuple by level"}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef load(self, project_file=''):\n self._request_project_file(project_file)\n self.clear()\n self.desc.update(data_file.load(self._project_file))", "response": "Load the description from a YML file."}
{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef save(self, project_file=''):\n self._request_project_file(project_file)\n data_file.dump(self.desc.as_dict(), self.project_file)", "response": "Save the description as a YML file."}
{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a color from the Palette.", "response": "def get(self, position=0):\n \"\"\"\n Return a color interpolated from the Palette.\n\n In the case where continuous=False, serpentine=False, scale=1,\n autoscale=False, and offset=0, this is exactly the same as plain old []\n indexing, but with a wrap-around.\n\n The constructor parameters affect this result as documented in the\n constructor.\n\n Arguments:\n ``position``:\n May be any integer or floating point number\n \"\"\"\n n = len(self)\n if n == 1:\n return self[0]\n\n pos = position\n\n if self.length and self.autoscale:\n pos *= len(self)\n pos /= self.length\n\n pos *= self.scale\n pos += self.offset\n\n if not self.continuous:\n if not self.serpentine:\n return self[int(pos % n)]\n\n # We want a color sequence of length 2n-2\n # e.g. for n=5: a b c d | e d c b | a b c d ...\n m = (2 * n) - 2\n pos %= m\n if pos < n:\n return self[int(pos)]\n else:\n return self[int(m - pos)]\n\n if self.serpentine:\n pos %= (2 * n)\n if pos > n:\n pos = (2 * n) - pos\n else:\n pos %= n\n\n # p is a number in [0, n): scale it to be in [0, n-1)\n pos *= n - 1\n pos /= n\n\n index = int(pos)\n fade = pos - index\n if not fade:\n return self[index]\n\n r1, g1, b1 = self[index]\n r2, g2, b2 = self[(index + 1) % len(self)]\n dr, dg, db = r2 - r1, g2 - g1, b2 - b1\n\n return r1 + fade * dr, g1 + fade * dg, b1 + fade * db"}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nwait for the event run the task trigger the next task.", "response": "def run(self, next_task):\n \"\"\"Wait for the event, run the task, trigger the next task.\"\"\"\n self.event.wait()\n self.task()\n self.event.clear()\n\n next_task.event.set()"}
{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nruns a function catch report and discard exceptions", "response": "def report(function, *args, **kwds):\n \"\"\"Run a function, catch, report and discard exceptions\"\"\"\n try:\n function(*args, **kwds)\n except Exception:\n traceback.print_exc()"}
{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreceiving a message from the input source and perhaps raise an exception.", "response": "def _receive(self, msg):\n \"\"\"\n Receive a message from the input source and perhaps raise an Exception.\n \"\"\"\n msg = self._convert(msg)\n if msg is None:\n return\n\n str_msg = self.verbose and self._msg_to_str(msg)\n if self.verbose and log.is_debug():\n log.debug('Message %s', str_msg)\n\n if self.pre_routing:\n self.pre_routing.receive(msg)\n\n receiver, msg = self.routing.receive(msg)\n if receiver:\n receiver.receive(msg)\n if self.verbose:\n log.info('Routed message %s (%s) to %s', str_msg[:128], msg,\n repr(receiver))"}
{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nset the brightness of the device.", "response": "def set_device_brightness(self, val):\n \"\"\"\n APA102 & SK9822 support on-chip brightness control, allowing greater\n color depth.\n\n APA102 superimposes a 440Hz PWM on the 19kHz base PWM to control\n brightness. SK9822 uses a base 4.7kHz PWM but controls brightness with a\n variable current source.\n\n Because of this SK9822 will have much less flicker at lower levels.\n Either way, this option is better and faster than scaling in\n BiblioPixel.\n \"\"\"\n # bitshift to scale from 8 bit to 5\n self._chipset_brightness = (val >> 3)\n self._brightness_list = [0xE0 + self._chipset_brightness] * self.numLEDs\n self._packet[self._start_frame:self._pixel_stop:4] = (\n self._brightness_list)"}
{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nadding a new logging level to the logging module and the logging class.", "response": "def _addLoggingLevel(levelName, levelNum, methodName=None):\n \"\"\"\n Comprehensively adds a new logging level to the `logging` module and the\n currently configured logging class.\n\n `levelName` becomes an attribute of the `logging` module with the value\n `levelNum`. `methodName` becomes a convenience method for both `logging`\n itself and the class returned by `logging.getLoggerClass()` (usually just\n `logging.Logger`). If `methodName` is not specified, `levelName.lower()` is\n used.\n\n To avoid accidental clobberings of existing attributes, this method will\n raise an `AttributeError` if the level name is already an attribute of the\n `logging` module or if the method name is already present\n\n Example\n -------\n >>> addLoggingLevel('TRACE', logging.DEBUG - 5)\n >>> logging.getLogger(__name__).setLevel(\"TRACE\")\n >>> logging.getLogger(__name__).trace('that worked')\n >>> logging.trace('so did this')\n >>> logging.TRACE\n 5\n\n \"\"\"\n if not methodName:\n methodName = levelName.lower()\n\n if hasattr(logging, levelName):\n raise AttributeError(\n '{} already defined in logging module'.format(levelName))\n if hasattr(logging, methodName):\n raise AttributeError(\n '{} already defined in logging module'.format(methodName))\n if hasattr(logging.getLoggerClass(), methodName):\n raise AttributeError(\n '{} already defined in logger class'.format(methodName))\n\n # This method was inspired by the answers to Stack Overflow post\n # http://stackoverflow.com/q/2183233/2988730, especially\n # http://stackoverflow.com/a/13638084/2988730\n def logForLevel(self, message, *args, **kwargs):\n if self.isEnabledFor(levelNum):\n self._log(levelNum, message, args, **kwargs)\n\n def logToRoot(message, *args, **kwargs):\n logging.log(levelNum, message, *args, **kwargs)\n\n logging.addLevelName(levelNum, levelName)\n setattr(logging, levelName, levelNum)\n setattr(logging.getLoggerClass(), methodName, logForLevel)\n setattr(logging, methodName, logToRoot)"}
{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nsets the log level of the current log object", "response": "def set_log_level(level):\n \"\"\"\n :param level: the level to set - either a string level name from\n 'frame', 'debug', 'info', 'warning', 'error'\n or an integer log level from:\n log.FRAME, log.DEBUG, log.INFO, log.WARNING, log.ERROR\n \"\"\"\n if isinstance(level, str):\n level = LOG_NAMES[level.lower()]\n\n logger.setLevel(level)"}
{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef construct(cls, project, **desc):\n return cls(project.drivers, maker=project.maker, **desc)", "response": "Construct a layout.\n class."}
{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning an independent copy of this layout with a completely separate color_list and no drivers.", "response": "def clone(self):\n \"\"\"\n Return an independent copy of this layout with a completely separate\n color_list and no drivers.\n \"\"\"\n args = {k: getattr(self, k) for k in self.CLONE_ATTRS}\n args['color_list'] = copy.copy(self.color_list)\n return self.__class__([], **args)"}